2

問題は次のとおりです。ページにアイテムのリストがあり、それぞれに削除するための独自のリンク/ボタンがあります。現在、各ボタンはIDとアイテムの説明/名前をJS関数に渡す必要があるため、各ボタンにonclickがあります。

邪魔にならないようにしたいのですが、方法が思いつきません。助言がありますか?

以下は、現在のセットアップの例です。

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

1 に答える 1

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/

于 2011-11-17T16:18:21.107 に答える