unobtrusive javascript without function parameters

737 views Asked by At

if you have

<div id="data" onclick="handleData(1)">Datum 1</div>

and you want to late bind instead:

<div id="data">Datum 1</div>
<script>
    $("#data").click(function() {
        handleData(1);
    })
</script>

How do you pass that parameter 1? do you have to do something like this:

<div id="data" data="1">Datum 1</div>
<script>
    $("#data").click(function() {
        handleData($(this).attr("data"););
    })
</script>
3

There are 3 answers

1
user113716 On BEST ANSWER

I assume you're using jQuery.

If so, I'd take advantage of jQuery's support for the HTML5 data- attribute using the data()(docs) method . It will in all browsers.

<div id="data" data-number="1">Datum 1</div>
<script>
    $("#data").click(function() {
        handleData($(this).data("number"));
    })
</script>

Notice that I changed the attribute to data-number, and accessed it with .data("number"). This requires jQuery 1.4.3 or later.

From the docs:

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

0
Alexander Wallin On

Your last approach is almost correct. You should use the data attribute as a prefix in the form of data-someproperty. Then you might access it through $(this).data("someproperty") or $(this).attr("data-someproperty").

Edit: Read about: jQuery.data().

0
Dan Davies Brackett On

Assuming that there's more than one data element, yes, you'll have to pass that parameter some other way. It doesn't have to be in the HTML though:

<div class="data">one</div>
<div class="data">two</div>
<div class="data">three</div>

<script>
    $('.data').each(function(ix){$(this).click(function(){handleData(ix)})});
</script>

This is a bit of an abuse of document-ordering, but it's pretty unobtrusive.