gpt4 book ai didi

javascript - 从 ul 获取被点击的元素

转载 作者:搜寻专家 更新时间:2023-10-31 23:02:14 24 4
gpt4 key购买 nike

我正在使用 javascript 填充动态列表。我有一个 onclick Action ,我需要从列表中获取点击的项目。HTML 如下:

 <div class="cate-map">
<ul id="option1" onclick="doSelection()">

</ul>

</div>

我将列表填充为:

jQuery.get(url, function(data) {
for(i=0;i<data.length;i++){
msg = "<li data-input="+data[i]+" class='selected'> <a href=#>"+data[i]+"</a></li>";
document.querySelector('#option1').innerHTML += msg;
}
});

Onclick 监听器如下:

function doSelection(){

var id =$('#option1 li.selected').attr('data-input');
alert(id);

}

问题是每当我点击 li 时,我仍然得到列表的第一个元素。不是我点击的那个。请帮忙。

最佳答案

我建议您使用 Event Delegation使用 .on()委托(delegate)事件方法。

$(document).on('event','selector',callback_function)

事件处理程序只绑定(bind)到当前选中的元素;在您的代码进行事件绑定(bind)调用时,它们必须存在于页面上。

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

例子

$('#option1').on('click', 'li', function() {
var id = $(this).data('input');
alert(id);
});

$(document).ready(function() {
var data = [1, 2, 3];
for (var i = 0; i < data.length; i++) {
var msg = "<li data-input=" + data[i] + " class='selected'> <a href=#>" + data[i] + "</a></li>";
$('#option1').append(msg);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cate-map">
<ul id="option1">
</ul>
</div>

关于javascript - 从 ul 获取被点击的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27543677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com