单击事件jquery时选择ID
我有一个可以插入单词的div和input字段,用户可以在输入中键入单词并保存它们以显示在div display_单词上。 现在,我希望能够从该div中删除所选单词,并为这些单词分配一个动态ID,如下所示:单击事件jquery时选择ID,jquery,Jquery,我有一个可以插入单词的div和input字段,用户可以在输入中键入单词并保存它们以显示在div display_单词上。 现在,我希望能够从该div中删除所选单词,并为这些单词分配一个动态ID,如下所示: <div id="display_words"> <div class="clhotpages" id="word1">word1</div> <div class="clhotpages" id="word2">word2<
<div id="display_words">
<div class="clhotpages" id="word1">word1</div>
<div class="clhotpages" id="word2">word2</div>
</div>
$("#display_words").on('click','.clhotpages',function(){
$(this).remove();
});
现在我希望能够让用户在单击事件时从div中删除一个单词
但我不知道如何从div获取ID,因为ID是动态的。
谢谢你能行
$(".clhotpages").click(function() {
var currentID = $(this).attr("id");
$(this).remove();
});
您可以使用提取特定属性
$(".clhotpages").live('click', function() {
$(this).attr('id');
});
也就是说,您实际上不必提取id来删除元素。在click回调中,可以使用$this变量来引用被单击的实际元素。所以你可以这样做-
$(".clhotpages").live('click',function(){
$(this).remove();
});
您可能还希望使用作为.live的替换。.live函数正在被弃用。使用.on,您的代码如下所示:
<div id="display_words">
<div class="clhotpages" id="word1">word1</div>
<div class="clhotpages" id="word2">word2</div>
</div>
$("#display_words").on('click','.clhotpages',function(){
$(this).remove();
});
我假设页面加载时存在display_words元素
尝试:
.live已被弃用,取而代之的是.on,并在jQuery 1.9中被完全删除。更重要的是,当您动态添加元素时,您需要通过委托元素与on绑定。我建议:
$(".clhotpages").click(function(){
alert($(this).attr('id'));
});
$('#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
});
jQuery 1.7+中支持on方法,live从1.7开始就不推荐使用,从1.9开始删除。但是,在jQuery1.7之前,建议使用委托而不是实时委托
对于代表,上述内容应写成:
$('#display_words').delegate('div.clhotpages', 'click', function(e){
var id = this.id; // or e.target.id
$(e.target).remove();
});
参考资料:
.
.
.