質問

I am using jQuery 1.4.2. Using the CSS selector "span.accordionOn", I am handling a click event. On screen one, it is working fine. Where as when I navigate to next screen, the functions are not getting called.

The jQuery handlers are as shown below. I am keeping them in a js file and loading the js file for every page load.

 $("span.accordionOn").click(function(event){
    $(this).parents(".toggleOuterCustom");
    $(this).parents(".toggleOuterCustom").find(".lHeight").toggleClass('lHeighttranslate');
    return false;
  });




// toggle link icon
  $('span.accordionOn').click(function(){
    $(this).toggleClass('accordionOff');
  });
役に立ちましたか?

解決

Without seeing more code it will be hard to find the exact issue, but here's a guess:

 $(document).on("click", "span.accordionOn", function(event){
    $(this).toggleClass('accordionOff'); //I merged the 2 functions
    $(this).parents(".toggleOuterCustom");
    $(this).parents(".toggleOuterCustom").find(".lHeight").toggleClass('lHeighttranslate');
    return false;
  });

Try the above code. If this works then the issue is as following:

  • You bind the event handler to all span.accordionOn elements that are currently in the document
  • However, if you add new span.accordionOn elements after this, the event will not be bound to them
  • The on event will work for all current and future span.accordionOn items that will ever be in the document, which solves this issue

他のヒント

I found the issue. yes, you are right, elements do not exist when I am trying to bind.

However with jQuery 1.4.2, 'on()' doesn't exist and used 'live'. Here is the code.

  $("span.accordionOn").live('click',function(event){
    $(this).parents(".toggleOuterCustom");
    $(this).parents(".toggleOuterCustom").find(".lHeight").toggleClass('lHeighttranslate');
    return false;
  });
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top