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

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

问题描述

可能的重复:
jQuery .attr 检索自定义属性返回未定义

我遇到了一个奇怪的问题,但我希望我只是在做一些愚蠢的事情.我正在尝试使用 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 函数,并将 this 作为参数传递.我已经检查了方法中的对象,并且传递了正确的对象;属性设置的事实(即使设置了错误的值)也支持这一点.

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.

推荐答案

Selected 已经是 HTML 标准中的一个属性,因此您不能创建具有相同名称的自定义属性.在这种情况下,您应该改用 data- 属性并创建一个属性 data-selected 例如.

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天全站免登陆