[英]jQuery attr() method to create a data dash attribute
I'm trying to figure out why when adding a data-attribute to (Let's say an image) requires the attribute name to be put into quotes. 我试图弄清楚为什么在添加数据属性时(比如说图像)需要将属性名称放入引号中。 I know that it needs to be done, but if a student asked me I wouldn't have the exact answer why.
我知道它需要完成,但如果一个学生问我,我不会得到确切的答案。 So take the two examples below.
所以请看下面的两个例子。
1.) I'm looking for an explanation why the dash is a problem. 1.)我正在寻找一个解释为什么短跑是一个问题。
2.) Is there a way to escape it so you don't need to put it in quotes? 2.)有没有办法逃脱它,所以你不需要把它放在引号?
This Doesn't work: 这不起作用:
$("img").attr({
alt: "a picture of my cat",
data-item : "pet",
data-color : "orange",
});
This Does work 这确实有效
$("img").attr({
alt: "a picture of my cat",
'data-item' : "pet",
'data-color' : "orange",
});
3.) The arguments that are passed to the attr() method is an object literal right? 3.)传递给attr()方法的参数是对象文字对吗?
4.) Is this just a rule in object literal syntax that a dash is not allowed? 4.)这只是对象文字语法中的规则,不允许使用破折号吗?
1.) In object literals, the -
symbol is not allowed as an identifier because it is also the minus operator in javascript. 1.)在对象文字中,
-
符号不允许作为标识符,因为它也是javascript中的减号运算符。
2.) no, you have to use quotes. 2.)不,你必须使用报价。
3.) yes. 是的。
4.) yes, see 1. 4.)是的,见1。
I agree with @Ferdi265 . 我同意@ Ferdi265 。
However one additional point I would make is to use jQuery.data()
. 但是,我要做的另一点是使用
jQuery.data()
。
jQuery.data()
doesn't actually update the DOM, it updates a javascript object referencing the element and stores the value there. jQuery.data()
实际上并不更新DOM,它更新引用该元素的javascript对象并将值存储在那里。
It's much better for performance as no DOM manipulation is required. 它的性能要好得多,因为不需要DOM操作。
$("img").attr({
alt: "a picture of my cat"
}).data({
item: "pet",
color: "orange"
});
Obviously this doesn't update your element's attributes, and therefore any future reference to these values will have to be done with jQuery.data()
; 显然,这不会更新元素的属性,因此将来对这些值的任何引用都必须使用
jQuery.data()
;
$("img").data("item");
If you're interested in understanding how this works under-the-hood I wrote an article on it a while back: 如果你有兴趣了解它是如何工作的,我会在一段时间后写一篇文章:
http://curtistimson.co.uk/jquery/understanding-jquery-data-storage/ http://curtistimson.co.uk/jquery/understanding-jquery-data-storage/
this is how I worked around it: 这是我如何解决它:
.attr({ style: "font-size : 50px;background-color : powderblue;font-family:arial" })
as a specific example of how to specify multiple attributes in an element creation statement. 作为如何在元素创建语句中指定多个属性的具体示例。 This is after the above examples did not work.
这是在上面的例子不起作用之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.