2

I have the following html code:

<div>
  <span>Products per page:</span>
  <a class="selectview" href="/womens-clothing/shorts?page=1&view=20">20</a>
  <a class="selectview" href="/womens-clothing/shorts?page=1&view=200">200</a>
<div>

and the jQuery is as follows:

jQuery('.selectview').click(function (ev) {

  ev.preventDefault();

  var alink = jQuery(this).attr('href'); 

  var view = getLinkVars(alink)["view"]; 
  var page = jQuery("#currentpageno").val();

  alert(alink);
  alert(view);
  alert(page);

  run_ajax(view,page);


});

The code runs fine the first time if I click on any of the links; I see the alerts and the ajax code runs fine, but when I click on it the second time, the whole page is refreshed and no alerts are shown. Then if I click on it again it works, then when I click on it again it works, and so on.

What could I be doing wrong?

4

2 回答 2

7

My guess is that run_ajax is replacing the links with new ones. .click only binds to the elements that matched the selector at that time. The newly added links won't have a click event bound to them.

You need to make the events "live". Bind them using .on like so:

jQuery(document).on('click', '.selectview', function (ev) {
    ev.preventDefault();
    // code...
});

This will "delegate" the event. It will run for all .selectview links no matter when they are added to the DOM.

于 2012-04-04T18:11:30.120 回答
0

If run_ajax is replacing the links you can wrap the code that attaches your click handlers, and then inside run_ajax you can call the wrapper after you've replaced the links with the new content:

var setupClickHandlers = function(container) {
    jQuery(container).find('.selectview').click(function (ev) {

        ev.preventDefault();

        var alink = jQuery(this).attr('href'); 

        var view = getLinkVars(alink)["view"]; 
        var page = jQuery("#currentpageno").val();

        alert(alink);
        alert(view);
        alert(page);

        run_ajax(view,page);
    });
};
setupClickHandlers(container);

The in run_ajax:

var run_ajax = function(view, page) {
    // do your stuff here

    // set up click handlers on the new content
    setupClickHandlers(container);
}
于 2012-04-04T18:24:51.500 回答