使用html“data-”属性

时间:2013-07-19 15:27:03

标签: javascript html5 html

考虑如下这样的一行:

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

现在,假设它已扩展为更像这样的东西:

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

这里没有功能差异,但这是我的问题。我正在寻找一种方法将'data-something'的值传递给DoSomething函数而不是id。我似乎无法找到这样做的方法?有可能吗?

像下面这样的东西会很好,但当然不是它的工作方式。 (我只是用它来帮助说明预期的目标。

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

4 个答案:

答案 0 :(得分:10)

你可以做到

DoSomething(this.dataset.something)

但通常建议将javascript部分和HTML分开,这在元素具有id时特别容易:

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

在Internet Explorer上,support for dataset is incomplete。在IE10-上,您需要使用

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

答案 1 :(得分:5)

您应该可以this.getAttribute("data-something")执行此操作:

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

或者您可以使用this.dataset.something

Here is my source

答案 2 :(得分:1)

您应该使用getAttribute方法:

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

但我强烈建议你将内联javascript委托给元素。您应该更好地使用DOM或jQuery,并注意 jQuery 有一种方法可以更轻松地处理数据 - * 属性。

答案 3 :(得分:0)

如果你想考虑jQuery,你可以在这样的事情中转换你的代码:

<强> HTML

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

<强>的jQuery

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

或更好

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

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