views:

98

answers:

4
var dayNumberCell = doc.createElement('td');
  dayNumberCell.className = 'days_link';
      dayNumberCell.setAttribute('onclick', function(scope) {
                                            var bindScope = function()    {
                                                scope.changeDate(this, this.id);
                                                scope.returnDate(scope.month, scope.year);
                                            };
                                            return bindScope;
                              }(this));

The above code generates tds onclick event listener. and the generated code looks like

    <td class="days_link" onclick="function () {
    scope.changeDate(this, this.id);
    scope.returnDate(scope.month, scope.year);
}">15</td>

By clicking on TD I get syntax error message. How should I write my function that the specified code executes and also have no syntax error.

Thanks in advance.

A: 

You put your function definition inside a string literal. It's expecting code and all it has is text.

Joel Coehoorn
A: 

You should rewrite your onclick handler as follows:

dayNumberCell.onclick = function(e) {
   var target = e.target || e.srcElement;
   target.changeDate(target, target.id);
   target.returnDate(target.month, target.year);

   return false;
};

I don't understand why you would try to set the inline click handler from an external js file. You took the right step to remove inline click handlers from your html, but when you set the click handler from an external script, you should not be setting the onclick attribute.

In addition to the way I highlighted, you could use the w3c and microsoft event handlers so that you can attach multiple onclick events to the same element. However, this is a more complicated approach since different browsers handle it differently. This will suffice as long as you don't plan to have other onclick handlers attached to the same cell.

Keith Rousseau
A: 
    <td class="days_link" onclick="function () {
    scope.changeDate(this, this.id);
    scope.returnDate(scope.month, scope.year);}">15</td>

Have you tried outside the function?

    <td class="days_link" onclick="scope.changeDate(this, this.id);scope.returnDate(scope.month, scope.year);">15</td>

if that don't work, try it on your javascript file, and there, yes, with a function.

CuSS
A: 

Perhaps you would prefer not to use any javascript libraries, but I would highly recommend using the YUI Event utility for this. Dustin Diaz has a great article that explains how it would simplify this for you.

http://www.dustindiaz.com/yahoo-event-utility/

einarq