jQuery 按钮处理程序与内联 onClick

发布于 2024-12-16 20:41:21 字数 676 浏览 7 评论 0原文

问题是这样的: 我在页面上有一个项目列表,每个项目都有自己的链接/按钮来删除它。目前,我在每个按钮上都有一个 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 -->

Here's the problem:
I have a list of items on a page, each with its own link/button to delete it. Currently, I have an onclick on each button because each button needs to pass the id and a description/name of the item to a JS function.

I would like to make it less obtrusive, but can't think of a way. Any suggestions?

Here is an example of the current setup:

function doButtonThings(id, desc) {
    //jQuery to do some stuff and then remove the item from the page
}

And 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 -->

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

往日情怀 2024-12-23 20:41:21

您可以将数据存储在 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/

You can store the data in HTML data attributes:

<button data-myId="1001" data-myDescr="The thing we delete">Click me</button>

And then use them in a jQuery click handler:

$('button').click(function() {
    var $this = $(this),
        id = $this.data('myid'),
        descr = $this.data('mydescr');

    doButtonThings(id , descr );
});

Here is a fiddle to illustrate: http://jsfiddle.net/didierg/fhLde/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文