2013-05-01 97 views
0

我有一个div,我可以插入单词和输入字段,用户可以在输入上键入单词并保存它们以显示在div“display_words”上。 现在我希望能够从该分区删除选定的话,我那些话分配一个动态的ID,它看起来像这样:点击事件选择ID jquery

<div id="display_words"> 
    <div class="clhotpages" id="word1">word1</div> 
    <div class="clhotpages" id="word2">word2</div> 
</div> 

我有可以检测他们点击一个功能类“clhotpages”:

 $(".clhotpages").live('click', function() { 
     //GET ID TO REMOVE THAT WORD 
     alert("click"); 
     }); 

现在我希望能够让用户从点击事件中的div上移除单词。

但我不知道如何从div中获取ID,因为ID是动态的。 感谢

回答

4

我建议:jQuery中被支撑

$('#display_words').on('click','div.clhotpages', function(e){ 
    var id = this.id; // or e.target.id; gets the id 
    $(e.target).remove(); // removes the word 
}); 

on()方法1.7+(和live()被弃用的1.7,并且如1.9移除)。在jQuery 1.7之前,推荐使用delegate()而不是live()

随着delegate()以上的将被写成:

$('#display_words').delegate('div.clhotpages', 'click', function(e){ 
    var id = this.id; // or e.target.id 
    $(e.target).remove(); 
}); 

参考文献:

0

你可以做

$(".clhotpages").click(function() { 
    var currentID = $(this).attr("id"); 
    $(this).remove(); 
}); 
0

可以使用.attr() function提取特定属性。

$(".clhotpages").live('click', function() { 
    $(this).attr('id'); 
}); 

这就是说,你不需要提取id以删除元素。在点击回调中,您可以使用$(this)变量来引用被点击的实际元素。所以,你可以做这样的事情 -

$(".clhotpages").live('click',function(){ 
    $(this).remove(); 
}); 

您可能还需要使用.on() function.live()的替代品。 .live()函数正在被弃用。使用.on(),你的代码应该是这样的:

$("#display_words").on('click','.clhotpages',function(){ 
    $(this).remove(); 
}); 

我假设#display_words元素存在的页面加载时。

3

尝试:

$("#display_words").on('click', '.clhotpages', function() { 
    var id = $(this).attr('id'); 
    alert("click"); 
}); 

.live(),取而代之的.on()被废弃,完全的jQuery 1.9移除。更重要的是,当你动态添加元素时,你需要通过一个委托元素来绑定。

0
$(".clhotpages").click(function(){ 
    alert($(this).attr('id')); 
});