追加< li>元素到< ul>并为每个添加点击事件? [英] Append <li> element to <ul> and add click event for each?
问题描述
我想在< ul>
中添加一系列< li>
元素,并以编程方式为每一个添加一个click事件。
I'd like to add a series of <li>
elements to a <ul>
, and add a click event to each one, programmatically.
我不知道如何做到这一点,至少不是以一种简洁的jQueryish方式。
I'm not sure how to do this, at least not in a neat, jQueryish way.
这是我现有的代码:
<ul id="saved-list"></ul>
<script type="text/javascript">
$.each(all_objects, function() {{
var list_route = "<li><a href='#saved-route'>" + this.text + "</a></li>";
$('#saved-list').append(list_route);
// add unique id (this.id) to item and click event here?
// pseudocode - onclick: alert(this.id);
});
$('#saved-list').refresh('listview'); // jquery mobile list refresh
</script>
有人可以建议如何以编程方式为每个列表项添加点击事件吗?
Please could someone advise how to add a click event to each list item programmatically?
更新:我需要为每个列表项做一些略微不同的事情(我们只是说一个提醒) - 道歉没有说清楚。
UPDATE: I need to do something slightly different for each list item (let's just say an alert) - apologies for not making this clear.
推荐答案
最好使用 .live()
或 .delegate()
而不是担心在您创建的每个元素上创建 .click()
处理程序。这样的事情:
You're better off using .live()
or .delegate()
than worrying about creating a .click()
handler on every element you create. Something like this:
$('#saved-list').delegate('li', 'click', function () {
// do stuff on click
});
你只需要绑定一次点击监听器,它就可以用于每个< li>
这是ID saved-list
元素的后代。
You only have to bind this click listener once, and it will work for every <li>
that is a descendant of the element with ID saved-list
.
如果你想为每个< li>
创建一个单独的点击处理程序(我不推荐这个虽然这里有一个很好的方法:
If you do want to create a separate click handler for every <li>
(I don't recommend this though) here's a nice way to do it:
$.each(all_objects, function() {
var $a = $('<a/>', {
href: '#saved-route',
text: this.text
});
var $li = $('<li/>', {
click: function () {
// do stuff on click
}
}).append($a);
$('#saved-list').append($li);
});
这篇关于追加< li>元素到< ul>并为每个添加点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!