这里我正在创建一个购物 list ,我有一个文本框用于输入项目和提交按钮以将项目添加到数组中。 提交后,该项目将被推送到数组,并且列表将得到更新。我想做的是,当我单击任何列出的项目时,我应该能够获取其 id,但我无法获取它。我该如何解决这个问题?
这是我所做的:
'use strict';
(function() {
var itemslist = [];
$('#addList').click(function(e) {
var item = $('#itemname').val();
if (item == '') {
alert('Cannot be empty!')
return false;
} else {
e.preventDefault();
itemslist.push(item);
update();
}
})
var update = function() {
$('#shopList').empty();
itemslist.forEach(function(value, index) {
$('#shopList').append("<section id='" + index + "' class='items-list'>" + value + "</section>") //list-item gets appended after the successful push of item to array
})
}
$('.items-list').click(function() {
console.log(this.id); //unable to get the clicked element id
})
})(window);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<form method="post" name="listform">
<input id="itemname" type="text" value="" name="item" placeholder="Ex: butter and milk" required>
<button class="btn btn-peace" id="addList"><i class="fa fa-shopping-cart" aria-hidden="true"></i> Add to List</button>
</form>
</div>
<div id="shopList">
</div>
最佳答案
$(this).attr('id')
应该可以解决问题
该函数不起作用,因为它未绑定(bind)到动态创建的元素。
要绑定(bind)它,请选择层次结构中较高的元素,然后检查单击了哪个元素。您可以按如下方式执行此操作:
$(body).on('click','.items-list', function() {
console.log($(this).attr('id') );
});
关于javascript - jquery如何获取被点击的元素id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44925036/