简体   繁体   中英

jQuery calls after HTML DOM selectors has been updated

When the document is ready, I am preparing click functions to some of the elements in such a way:

var divs = $("div a");
divs.click(function(){
  alert("clicked");

  return false;
});


var spans = $("span a");
spans.click(function(){
  $("div").append("<a>Another link</a>");
  alert("done");

  return false;
});

As you can notice, when user clicks on a link inside a <span> , I am appending new anchor into <div> element with append() function.

And than, when I click on those, just appended new anchors inside <div> , I am not getting alert("clicked") , which has to be?! But when clicking on default anchors, which hasn't been appended, alert still works for them?!


Than I am changing the code wrapping first part into a function:

function activateClick(){
  var divs = $("div a");
  divs.click(function(){
    alert("clicked");

    return false;
  });
}

// calling a function when page has been loaded
// to allow clicking on default anchors
activateClick();

var spans = $("span a");
spans.click(function(){
  $("div").append("<a>Another link</a>");

  // calling a function when new anchors appended
  activateClick();
  alert("done");

  return false;
});

And at the end, new anchors, which has been appended into <div> , are giving an alert("clicked") , but those default ones, gives this alert() more than one time , depends on how many times I have been called a function?!

Why so?! I need that always one alert appear!

Use .live() here so it works on anchors created later:

$("div a").live("click", function(){
  alert("clicked");    
  return false;
});

$("span a").click(function(){
  $("div").append("<a>Another link</a>");
  alert("done");
  return false;
});

If you always have that one <div> , then use .delegate() instead, which is a bit cheaper, like this:

$("div").delegate("a", "click", function(){
  alert("clicked");    
  return false;
});
var spans = $("span a");

spans.click(function(){
  var __a = $("<a>Another link</a>").appendTo("div");
  __a.click(function() {
      alert("clicked");
      return false;
  });
  alert("done");
  return false;
});

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