html“数据-"属性作为javascript参数 [英] html "data-" attribute as javascript parameter
问题描述
假设我有这个:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this.data.uid, this.data-name, this.data-value)">
还有这个:
function fun(one, two, three) {
//some code
}
好吧,这行不通,但我完全不知道为什么.有人可以发布一个工作示例吗?
Well this is not working but I have absolutely no idea why. could someone post a working example please?
推荐答案
获取data-*
属性的最简单方法是使用element.getAttribute()
:>
The easiest way to get data-*
attributes is with element.getAttribute()
:
onclick="fun(this.getAttribute('data-uid'), this.getAttribute('data-name'), this.getAttribute('data-value'));"
演示: http://jsfiddle.net/pm6cH/
虽然我建议只将 this
传递给 fun()
,并获取 inside 的 3 个属性 fun
> 功能:
Although I would suggest just passing this
to fun()
, and getting the 3 attributes inside the fun
function:
onclick="fun(this);"
然后:
function fun(obj) {
var one = obj.getAttribute('data-uid'),
two = obj.getAttribute('data-name'),
three = obj.getAttribute('data-value');
}
演示: http://jsfiddle.net/pm6cH/1/
通过属性访问它们的新方法是使用 dataset
,但并非所有浏览器都支持这种方式.你会像下面这样得到它们:
The new way to access them by property is with dataset
, but that isn't supported by all browsers. You'd get them like the following:
this.dataset.uid
// and
this.dataset.name
// and
this.dataset.value
演示: http://jsfiddle.net/pm6cH/2/
另请注意,在您的 HTML 中,此处不应有逗号:
data-name="bbb",
<小时>
参考:
element.getAttribute()
:https://developer.mozilla.org/en-US/docs/DOM/element.getAttribute.dataset
:https://developer.mozilla.org/en-US/docs/DOM/element.dataset.dataset
浏览器兼容性:http://caniuse.com/dataset
element.getAttribute()
: https://developer.mozilla.org/en-US/docs/DOM/element.getAttribute.dataset
: https://developer.mozilla.org/en-US/docs/DOM/element.dataset.dataset
browser compatibility: http://caniuse.com/dataset
这篇关于html“数据-"属性作为javascript参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!