Change custom attribute values

前端 未结 2 674
庸人自扰
庸人自扰 2021-01-29 12:12

I have some code where I\'ve added custom attributes which I want to change the value of.

相关标签:
2条回答
  • 2021-01-29 12:37

    Firstly, inventing your own attributes will mean your HTML is invalid and can lead to issues in your page. Secondly, val() is used to directly change the value property of the element, hence why it has no effect in your example.

    To achieve what you require, use data-* attributes, as they are intended for this purpose:

    <div data-custom="someValue"></div>
    
    $("#somebutton").click(function() {
        // getter:
        var foo = $('div').data('custom'); // = 'someValue'
    
        // setter:
        $('div').data('custom', 'someOtherValue');
    });
    

    Note that data() maintains an object in memory so any amendments you make won't be visible in the DOM.

    For more information: http://api.jquery.com/data

    0 讨论(0)
  • 2021-01-29 12:38

    Your element isn't custom, it's still a div.

    You can do a custom element like so.

    <myCustomElement></myCustomElement>
    

    Then select like

    $('myCustomElement')...
    

    An alternative is to use data-attributes.

    <div data-myCustomData="test"></div>
    

    Then select like so

    var data = $('div').data('myCustomData')//data = 'test'
    
    0 讨论(0)
提交回复
热议问题