O.O
O.O

Reputation: 11287

Why is re-added click event not firing?

My html is rendered like this:

<td colspan="2" onclick="reportTypeClick(this);" class="menuItem oneTest">...</td>

Now I want to disable/enable the td as well as the click event:

if(...) {
    $('.oneTest').removeClass('menuItem').addClass('menuItemDisabled')
    .attr('onclick', '');
} else {
    $('.oneTest').removeClass('menuItemDisabled').addClass('menuItem')
    .attr('onclick', 'reportTypeClick(this);');
}

The if works as expected, but the else doesn't. That is to say, I get no script errors, but the event fails to fire.

Any ideas?

Looks like it has something to do with this.

Upvotes: 2

Views: 96

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195971

You should remove the onclick attribute and use jquery event handling..

if(...) {
    $('.oneTest').removeClass('menuItem').addClass('menuItemDisabled')
    .unbind('click');
} else {
    $('.oneTest').removeClass('menuItemDisabled').addClass('menuItem').each(function(){
      var _this=this;
      $(this).bind('click', function(){ reportTypeClick(_this) ););
    });
}

Alternatively you could alter your reportTypeClick function..

function reportTypeClick(element)
{
  if ( $(element).is('.menuItemDisabled') ) return; // add this line as the first line ..

  // the current body of the function should follow..
}

Upvotes: 3

JMax
JMax

Reputation: 26591

Instead of adding the event via the attr function, could you use the click function ?

[edit] and unbind it with the jquery unbind function ?

Regards

Max

Upvotes: 1

Related Questions