html “data-” attribute as javascript parameter

前端 未结 6 921
说谎
说谎 2020-11-29 00:27

Lets say I have this:

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 01:14

    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:

    • 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

提交回复
热议问题