jQuery 中的 Rel 属性
我想创建动态 html,需要渲染为下面给出的代码:
<a rel="{gallery: 'gal', smallimage: 'a',largeimage: 'b'}" href="javascript:void(0);"><img src="x1.jpg"></a>
我在 jQuery 中编写了以下代码来实现上面的效果:
for(i=1; i<=4; i++){
var rela="{gallery:'gal', smallimage:'a', largeimage: 'b'}";
html += "<a href='javascript:void(0);' rel='"+rela+"' ><img src='x"+i+".jpg' /></a>";
}
但是当它执行时,它呈现如下:
<a 'b'}'="" largeimage:="" smallimage:'a',="" gal',="" rel="{gallery:" href="javascript:void(0);"><img src="x1" class="img1"></a>
I want to create dynamic html which needs to render as code given below:
<a rel="{gallery: 'gal', smallimage: 'a',largeimage: 'b'}" href="javascript:void(0);"><img src="x1.jpg"></a>
What I wrote following code in jQuery to achive above:
for(i=1; i<=4; i++){
var rela="{gallery:'gal', smallimage:'a', largeimage: 'b'}";
html += "<a href='javascript:void(0);' rel='"+rela+"' ><img src='x"+i+".jpg' /></a>";
}
But when it's executed it renders as below:
<a 'b'}'="" largeimage:="" smallimage:'a',="" gal',="" rel="{gallery:" href="javascript:void(0);"><img src="x1" class="img1"></a>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您自己发现的那样,使用属性来存储对象上的数据并不完全是一个聪明的想法,它不会像您希望的那样工作。尤其是json。
在你的例子中,你想存储 json 吗?或者在 html 中包含 qoutes 的对象,但是浏览器会将它遇到的第一个 qoute 视为 rel 属性的闭包。..把事情搞砸了。
将不同的属性存储在单独的数据属性中,或者考虑将项目存储在 js 变量中并将锚点存储在 id 中。当您再次需要数据时,您可以使用锚点上的 id 从 js 变量重新捕获数据。 (在此处了解有关数据属性的更多信息)。
Using attributes to store data on objects isn't exactly a smart idea as you found out yourself, it doesn't work as you might want it to work. Especially json.
In your case you're trying to store json? Or an object with qoutes in it in the html, the browser however will treat the first qoute it encounters as a closure of the rel attribute.. messing stuff up bigtime.
Store the different properties in a seperate data attribute, or considder storing the items in a js variable and the anchor an id. When you need the data again you use the id on the anchor to recapture the data from the js variable. (read more here on data attributes).
或者
or