Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unobtrusive javascript without function parameters

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>
like image 992
Joe Hanink Avatar asked Apr 09 '26 00:04

Joe Hanink


2 Answers

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.

like image 182
user113716 Avatar answered Apr 10 '26 13:04

user113716


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().

like image 43
Alexander Wallin Avatar answered Apr 10 '26 14:04

Alexander Wallin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!