jQuery Button Handler vs inline onClick

6.1k Views Asked by At

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

There are 1 best solutions below

5
On BEST ANSWER

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/