开发者

Append element problem

开发者 https://www.devze.com 2023-04-02 06:24 出处:网络
I am creating some elements and appending it, and its working fine but when I want to call any function or want to call any jquery that not work, but when i put that elements directly instead of appen

I am creating some elements and appending it, and its working fine but when I want to call any function or want to call any jquery that not work, but when i put that elements directly instead of appending then it works properly. In all to say that appending element does not call any function or anything.

JQUERY CODE:

var cart_content = jQuery($.create('li', {}, [])).append($.create('span',{}, [av_title]),$.create('img', {"src开发者_如何学Go":"images/delete_icon.png", "class":"cart_content", "alt":"delete", "title":"Delete"}, []));
$(".advertise_cart").append(cart_content);


$(".cart_content").click(function(){    alert("Hello"); });
<ul class="advertise_cart" id="advertise_cart_id">
   <li>
        <span>Inner Content 1</span>
        <img src="images/delete_icon.png" class="cart_content" alt="delete" title="Delete">    <!------ On clicking on this will show alert box, but on clicking on appended element will not call alert box or anything ----->
    </li>
</ul>

Thanks in advance


The problem you're experiencing is the result of the elements not being present in the DOM when the events are bound. To work around this, you can use delegate() or live():

$('body').delegate('.cart_content','click',
    function(){
        alert('hello');
    });

JS Fiddle demo.

References:

  • live().
  • delegate().


Do not use .click function.

Use live function it work for newly added element in DOM

like this :

$(".cart_content").live(function(){    alert("Hello"); });


Using the live function to handle your event might help.


The only thing I'd add is that the live function means that the handler will continue to be applied to content that matches the selector at any point in the future (until and unless you call unbind). That is probably what you want here. If it isn't, you could write could that would add the click handler after a brief delay (say, 1.5 seconds). Or to be a little more sure, you could write code that would check for the presence of .cart_content every 100 milliseconds until it's found, and then add the click handler. So this approach would add the click handler only once. If something caused another .cart_content were added later, the click handler would not automatically be added.

0

精彩评论

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

关注公众号