简体   繁体   中英

jquery click event executes multiple times inside setinterval function

i have used below code,

setInterval(loadnew, 5000);

function loadnew() {
    $(".lf-item .lf-item-inner .lf-item-link").load();
    $('.lf-item .lf-item-inner .lf-item-link').on('click', function()
    {
         alert('image');
    });
}

as .lf-item .lf-item-inner .lf-item-link items are loaded when page scroll. So i used setinterval for this but getting result multiple times like every 5000 ms created one image output when click event occur it thorough all output values.

please run and wait more than 5000 ms and click image. below link: http://jsfiddle.net/g3fkL736/

can any one help me on this issue?

Use unbind that will remove the event.

function loadnew() {
$(".lf-item .lf-item-inner .lf-item-link").load();
    $('.lf-item .lf-item-inner .lf-item-link').unbind('click');
    $('.lf-item .lf-item-inner .lf-item-link').on('click', function()
    {
         alert('image');
    });   

You could try this, Actually loadnew () called repeatly so before regiester event you need to remove the lisener for events like below.

Note that off("click") .

function loadnew() {

      $(".lf-item .lf-item-inner .lf-item-link").load();

      $('.lf-item .lf-item-inner .lf-item-link').off("click").on('click', function() {
             alert('image');
      }); 
}

Take the event binding outside the interval function, it's not needed there.

$('.lf-item .lf-item-inner .lf-item-link').on('click', function()
{
     alert('image');
});

setInterval(loadnew, 5000);

function loadnew() {
    $(".lf-item .lf-item-inner .lf-item-link").load();
}

You're setting the click handler over and over...

Instead, you can bind the .on() handler to the document, and add the selector as the second paramenter, so even if it does not exists at the time you create the handler, it will be processed at runtime.

setInterval(loadnew, 5000);
function loadnew() {
    $(".lf-item .lf-item-inner .lf-item-link").load();
}

$(document).on('click', '.lf-item .lf-item-inner .lf-item-link', function()
{
     alert('image');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM