数据 - “数据”属性作为javascript参数 [英] html "data-" attribute as javascript parameter

查看:193
本文介绍了数据 - “数据”属性作为javascript参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有这个:

 < div data-uid =aaadata-name =bbb ,data-value =ccconclick =fun(this.data.uid,this.data-name,this.data-value)> 

与此:

 函数fun(一,二,三){
//一些代码
}

那么这是行不通的,但我完全不知道为什么。有人可以发布一个工作示例吗?

解决方案最简单的方法获取 data - * c code $>元素.getAttribute():

  onclick =fun(this.getAttribute('data-uid'),this.getAttribute('data-name'),this.getAttribute('data-value')); 

DEMO: http://jsfiddle.net/pm6cH/






尽管我只是建议将这个传递给 fun(),并在<$ c>里面获得3个属性

$ p $ onclick =fun(this);

然后:

 函数fun(obj){
var one = obj.getAttribute('data-uid'),
two = obj.getAttribute('data-name'),
three = obj.getAttribute('data-value');
}

DEMO: http://jsfiddle.net/pm6cH/1/






通过属性访问它们的新方法是使用 dataset ,但所有浏览器都不支持。你会得到他们如下:

  this.dataset.uid 
//和
this .dataset.name
//和
this.dataset.value

DEMO: 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


  • Lets say I have this:

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

    And this:

    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?

    解决方案

    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'));"
    

    DEMO: http://jsfiddle.net/pm6cH/


    Although I would suggest just passing this to fun(), and getting the 3 attributes inside the fun function:

    onclick="fun(this);"
    

    And then:

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

    DEMO: http://jsfiddle.net/pm6cH/1/


    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
    

    DEMO: http://jsfiddle.net/pm6cH/2/


    Also note that in your HTML, there shouldn't be a comma here:

    data-name="bbb",
    


    References:

    这篇关于数据 - “数据”属性作为javascript参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆