简体   繁体   中英

Using an html “data-” attribute

Consider a line such as this:

<div id='abc' onclick='DoSomething(this.id)'></div>

Now, suppose it's expanded to be something more like this:

<div id='abc' data-something='whatever' onclick='DoSomething(this.id)'></div>

There's no functional difference here yet, but this is my question. I'm looking for a way to pass the value of 'data-something' to the DoSomething function instead of the id. I can't seem to find a method of doing this? Is it possible?

Something like the following would be nice, but of course it's not how it works. (I'm only including it to help illustrate the intended goal.

<div id='abc' data-something='whatever' onclick='DoSomething(this.data-something)'></div>

You can do

DoSomething(this.dataset.something)

But it's generally recommended to separate the javascript part and the HTML, which is especially easy when your element has an id :

<div id='abc' data-something='whatever'></div>
<script>
    document.getElementById('abc').onclick = function(){
        DoSomething(this.dataset.something)
    }
</script>

On Internet Explorer, support for dataset is incomplete . On IE10-, You need to use

DoSomething(this.getAttribute('data-something'))

You should be able to do this.getAttribute("data-something") , like so:

<div id='abc' data-something='whatever' onclick='DoSomething(this.getAttribute("data-something"))></div>

or you can use this.dataset.something .

Here is my source

You should use getAttribute method:

<div id='abc' data-something='whatever' onclick='DoSomething(this.getAttribute("data-something")'></div>

But I highly suggest that you aviod inline javascript delegation to elements. You should better use DOM or jQuery for that and note that jQuery has a method for easier data-* attributes handling.

if you want consider jQuery you could convert your code in somethings like that:

html

<div id="abc" data-something="whatever">click here</div>

jQuery

jQuery(document).ready(function($) {
    $('#abc').on('click', function () {
        DoSomething($(this).attr('data-something'));
    });
});

or better

jQuery(document).ready(function($) {
    $('#abc').on('click', function () {
        DoSomething($(this));
    });
});

function DoSomething(obj){
    alert(obj.attr('id'));
    alert(obj.attr('data-something'));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM