Change custom attribute values

前端 未结 2 700
庸人自扰
庸人自扰 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:

    $("#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

提交回复
热议问题