开发者

initialize div after creating jquery

i have following code to show div on page

<div id="all_users">

 <div id=user11 userid=11 class=innertxt><img src=images/images.jpg width=50 height=50>    
 <strong>User11</strong>
  <ul> <li>Email: user11@uaer11.com</li>
  <li> <input type=checkbox id=select11 value=11 class=selectit /></li>
  </ul> </div>
 <div class="float_break"></div>

  </div>  

following code work fine and print "test in log window"

         $('#all_users .selectit').click(function() {
         console.log("test");
         });

but when i add div from following code, it didn't show "test in log windows" mean this click event is not activated

         var new_data_var = $('<div class="innertxt" userid="1" id="user1">开发者_C百科 <img height="50" width="50" src="images/images.jpg"><strong>Test User 01</strong><ul><li>User ID: 1</li> <li>Email: user1@nodomain.com</li><li style="padding-top: 5px;"><input type="checkbox" class="selectit" value="1" id="select1"><label for="select1">&nbsp;&nbsp;Select it.</label></li></ul></div>');
       $('#all_users').append(new_data_var);

event is not called ?

Thanks


You have to use live():

Binds a handler to an event (like click) for all current - and future - matched element.

For example:

$('#all_users .selectit').live('click', function() {
    console.log("test");
});

Right now you are using click() which delegates to bind().

The main difference is that live, contrary to bind, works also with newly created DOM elements.


live() method must do the trick there:

  $('#all_users .selectit').live('click', function() {
    console.log("test");
  });

Description: Attach a handler to the event for all elements which match the current selector, now or in the future.

Source: http://api.jquery.com/live/


you should check that your binding the click after the dom element is created or replace bind with live which behave similarly but also affect not yet existing element.

ps: your html attribute values should be quoted. eg, type=checkbox => type="checkbox"


If you are setting the click event before you create the input box, the click event will not be registered - it will only register the click event for DOM elements that exist at that time. You can either create the input box before calling $('#all_users .selectit').click(function() { ... or by using the live() function as others have suggested, which will attach the click event for all elements that match the selector and all elements in the future.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜