开发者

Trouble interacting with add span inside span - jQuery

开发者 https://www.devze.com 2023-03-15 19:19 出处:网络
First question here! I\'m trying to create a mail system and now working on setting up the list of receivers. I am adding the names of the users to a span, and want to remove users by clicking the nam

First question here! I'm trying to create a mail system and now working on setting up the list of receivers. I am adding the names of the users to a span, and want to remove users by clicking the name.

<span id="to"></span>

my script:

$("#auto").autocomplete($("#base_uri").val()+'search',{
        req_type: "POST",
        minChars: 1,
        delay: 200
        }开发者_开发技巧).result(function(event, data, formatted) {
                if($("#to").html() == ''){
                    $("#to").prepend('<span id="'+data[1]+'">'+formatted+'</span>');
                }
                else {
                    $("#to").prepend('<span id="'+data[1]+'">'+formatted+', '+'</span>');
                }
                $("#fake_to").val($("#fake_to").val()+ data[1] +', ');
                $("#auto").val('');
        });

$("#to span").click(function(){
        $(this).hide();
    });

data[1] and formatted are strings containing names.

I thought this approach would add spans which could be hidden by clicking them. Somehow this isn't the case. Hiding is not done when clicking the text in the add span..

Help would be most appreciated! =)


This should work:

$("#to").delegate('span', 'click', function() {
   $(this).hide();
});

I would suggest using .delegate() over .live() since you can specify a context the listening event gets attached to, where .live() attaches the event to the document itself.


You need to change :

$("#to span").click(function(){
        $(this).hide();
    });

to :

$("#to span").live('click',function(){
        $(this).hide();
    });

The .click binding only binds to the spans that were in existence when the code was executed. .live applies also to any instances created in the future.

0

精彩评论

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