使用jQuery创建一个新属性 [英] Creating a new attribute with jQuery

查看:131
本文介绍了使用jQuery创建一个新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

jQuery .attr检索自定义属性返回undefined





<我有一个奇怪的问题,但我希望我只是做一些愚蠢的事情。我正在尝试使用jQuery在< img> 元素上创建一个新属性,这一行:

I've got a weird problem, but I'm hoping I'm just doing something stupid. I'm trying to create a new attribute on an <img> element using jQuery, and this line:

$(selector).attr('selected', 'no');

当我在Chrome中检查DOM时,我只看到selected =selected,无论我是什么将值设置为。

When I inspect the DOM in Chrome, I just see selected="selected", no matter what I set the value to.

只是一些额外的信息:我不能只使用布尔值,因为我需要跟踪是,否和部分财产价值。我正在从img本身的onClick事件中调用JS函数,并将作为参数传递。我检查了方法中的对象,并传递了正确的对象;设置属性的事实(即使是错误的值)也支持这一点。

Just some extra info: I can't use just boolean values, as I need to keep track of "Yes", "No" and "Partial" property values. I'm calling a JS function from the "onClick" event of the img itself, and passing this as a parameter. I've inspected the object in the method, and the right object is passed; the fact that the attribute is set (even if to the wrong value) also supports this.

我确定我在这里做了一些愚蠢的事......任何事情建议将不胜感激。

I'm dead certain I'm doing something stupid here... Any advice would be appreciated.

推荐答案

已选择已经是HTML标准中的属性,因此您无法创建具有相同属性的自定义属性名称。在这种情况下,您应该使用 data - 属性,并创建一个属性数据选择

Selected is already an attribute in the HTML standard, so you cannot create a custom attribute with the same name. In that case, you should use the data- attributes instead and create an attribute data-selected for instance.

在jQuery中,您使用 处理自定义数据属性.data() 方法。

In jQuery you handle the custom data attributes using the .data() method.

自定义数据属性在HTML5规范中描述在其中

The custom data attributes are described in the HTML5 spec here.

这篇关于使用jQuery创建一个新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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