html"data-"属性作为javascript参数

Wer*_*ner 49 html javascript parameters

让我说我有这个:

<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this.data.uid, this.data-name, this.data-value)">
Run Code Online (Sandbox Code Playgroud)

还有这个:

function fun(one, two, three) {
    //some code
}
Run Code Online (Sandbox Code Playgroud)

嗯,这不起作用,但我完全不知道为什么.有人可以发一个工作实例吗?

Ian*_*Ian 88

获取data-*属性的最简单方法是element.getAttribute():

onclick="fun(this.getAttribute('data-uid'), this.getAttribute('data-name'), this.getAttribute('data-value'));"
Run Code Online (Sandbox Code Playgroud)

演示: http ://jsfiddle.net/pm6cH/


虽然我建议刚好路过thisfun(),并获得3个属性fun功能:

onclick="fun(this);"
Run Code Online (Sandbox Code Playgroud)

然后:

function fun(obj) {
    var one = obj.getAttribute('data-uid'),
        two = obj.getAttribute('data-name'),
        three = obj.getAttribute('data-value');
}
Run Code Online (Sandbox Code Playgroud)

演示: http ://jsfiddle.net/pm6cH/1/


按属性访问它们的新方法是dataset,但并非所有浏览器都支持.你可以得到以下内容:

this.dataset.uid
// and
this.dataset.name
// and
this.dataset.value
Run Code Online (Sandbox Code Playgroud)

演示: http ://jsfiddle.net/pm6cH/2/


另请注意,在HTML中,此处不应包含逗号:

data-name="bbb",
Run Code Online (Sandbox Code Playgroud)

参考文献: