更改自定义属性值 [英] Change custom attribute values

查看:88
本文介绍了更改自定义属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码在其中添加了要更改其值的自定义属性.

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

<div myCustomElement="someValue"></div>

这是我正在尝试的:

$("#somebutton").click(function() {
    $('myCustomElement').val('SomeNewValue');
});

但是什么都没有改变.我怎样才能使它正常工作?

But nothing's being changed. How can I get this to work?

推荐答案

首先,发明自己的属性将意味着您的HTML无效,并可能导致页面出现问题.其次,val()用于直接更改元素的value属性,因此为什么它在您的示例中无效.

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.

要实现您的要求,请使用data-*属性,因为它们是用于此目的的

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

请注意,data()在内存中维护一个对象,因此您所做的任何修改在DOM中都不可见.

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

有关更多信息: http://api.jquery.com/data

这篇关于更改自定义属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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