我想创建动态 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>
最佳答案
正如您自己发现的那样,使用属性在对象上存储数据并不完全是一个聪明的想法,它不会像您希望的那样工作。特别是 json。
在你的例子中,你想存储 json 吗?或者在 html 中包含 qoutes 的对象,但是浏览器会将它遇到的第一个 qoute 视为 rel 属性的闭包......把事情搞砸了。
将不同的属性存储在单独的数据属性中,或者考虑将项目存储在 js 变量中并将 anchor 存储在 id 中。当您再次需要数据时,您可以使用 anchor 上的 id 从 js 变量重新捕获数据。 (read more here on data attributes)。
关于javascript - jQuery 中的 Rel 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7475761/