这是问题所在: 我有一个页面上的项目列表,每个项目都有自己的链接/按钮来删除它。目前,我在每个按钮上都有一个onclick,因为每个按钮都需要将id和项目的描述/名称传递给JS函数。
我想让它不那么突兀,但想不出办法。有什么建议吗?
以下是当前设置的示例:
function doButtonThings(id, desc) {
//jQuery to do some stuff and then remove the item from the page
}
页面:
<!-- standard html page stuff -->
<ul>
<li><button onclick="doButtonThings(1001, 'The thing we delete');"></button> Some thing that can be deleted #1</li>
<!-- imagine many more list items this way with different ids and descriptions -->
</ul>
<!-- standard end of html page stuff -->
答案 0 :(得分:3)
您可以将数据存储在HTML数据属性中:
<button data-myId="1001" data-myDescr="The thing we delete">Click me</button>
然后在jQuery单击处理程序中使用它们:
$('button').click(function() {
var $this = $(this),
id = $this.data('myid'),
descr = $this.data('mydescr');
doButtonThings(id , descr );
});
这是一个小提琴来说明:http://jsfiddle.net/didierg/fhLde/