开发者

JQuery Access Elements in Modified DOM

im trying since a long term to use events on elements in my dom which has been added asynchronus. I´ve read something about bind but is there a different Way to etablish something like this?

For Example I have this situation.

$.getJQUERY(开发者_C百科myUrl, {var:value}, function(i, data){
  $.each(data.values, function(value){
      $("body").append('<div id="div_no_'+i+'">'+value+'</div>);
     // Here i dont want to place the EventListeners
  })
});
$("div_no_1").click(function(){
    // do something
});

Could someone help me to find a way to etablish something like this??

Thank you in advance

Great

Bernhard


You can use a .live() click handler like this:

$("div[id^=div_no_]").live('click', function(){
  // do something
});

This listens for clicks from existing or new elements that have IDs starting with div_no_

You only need this one time, it'll work for all the divs you create.

Jason's comment makes a lot of sense for your situation as well, something like this:

$.getJQUERY(myUrl, {var:value}, function(i, data){
  $.each(data.values, function(value){
      $("body").append('<div id="div_no_'+i+'" class="clickme">'+value+'</div>');
  })
});

$(".clickme").live('click', function(){
  // do something
});


This is a piggy-back off Nick's answer that may help you understand jQuery and Javascript a bit more:

$.getJQUERY(myUrl, {var:value}, function(i, data){
  $.each(data.values, function(value){
      var myDiv = document.createElement('div');
      $(myDiv).id('div_no_' + i).addClass('clickme').text(value);
      $('body').append(myDiv);
  })
});

$(".clickme").live('click', function(){
  // do something
});

The benefit with doing it this way is that it is more modular, should you decide to make changes/updates in the future. For instance, if you decide that you don't want it to be a div anymore, you can simply change the type of element created to, say, a span and that's the only change you need to make (granted in this example the variable is called myDiv but hopefully you name your variables better than that :). Basically, you're not rendering the HTML directly, but rather abstracting it so that jQuery/JS can do the heavy lifting for you.

Not trying to steal Nick's thunder, just providing an alternative, pedagogical example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜