首先你应该得到这样的rel
属性:
$(element).attr('rel');
其次,您可以将此字符串解析为 JSON 对象,但首先您必须确保您所拥有的rel
是格式良好的 JSON 对象。因此,使用单引号来包装rel
元素和双引号,如下所示:
<a rel='{"gallery": "gal1", "smallimage": "images/image1.jpg","largeimage": "images/image1.jpg"}'>
然后您可以使用 jQuery 解析 JSON 并将其用作对象,如下所示:
var src= $("a").attr("rel");
src = $.parseJSON(src);
您可以看到一个工作演示,其中我将src
用作对象:
Demo
您说您需要使用rel
,但是,正如评论中所建议的那样,更好的选择data
是您使用属性来存储此类数据,因为这是他们的工作,而不是rel
's。该HTML
元素看起来像这样:
<a data-gallery="gal1" data-smallimage="images/small.jpg" data-largeimage="images/large.jpg" href="#">
编辑:如何更改 rel 对象
您询问如何使用另一个图像标签的属性更改src
对象的一个src
属性。然后你会这样做:
// Get the attribute you want to substitute
var image = $('img').attr('src');
// Substitute it into the object properties
src.smallimage = image;
src.largeimage = image;
// Turn the object back into a string to put it back into the rel attribute
src = JSON.stringify(src);
$('a').attr('rel', src);