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>
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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With