1

我目前正在研究这个jquery 插件(一个图像放大镜)。

我发现许多 html 会为我想要放大的每个图像使用“a rel”或关系。

这是 rel 示例:

<a rel="{gallery: 'gal1', smallimage: 'images/image1.jpg',largeimage: 'images/image1.jpg'}">
    <img src = images/image1.jpg>
</a>

所以,我想将'smallimage'和'largeimage'(在rel内部)的值更改为变量。

我不确定 jquery 是否可以处理,我尝试编写一些这样的 jquery:

$(function(){
  var src= $("a:first").find('rel').attr();
});

但我认为它会将'rel'中的所有内容存储到变量src中

非常感谢你

4

2 回答 2

3

首先你应该得到这样的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);
于 2013-03-06T17:06:02.530 回答
1

看到这个:

$(function () {
    var src = $.parseJSON($("a:first").prop("rel"));
    src.smallimage = "images/newimage1.jpg";
    src.largeimage = "images/newimage1.jpg";

    alert("Before : " + $("a:first").prop("rel"));
    $("a:first").prop("rel", JSON.stringify(src));
    alert("After : " + $("a:first").prop("rel"));
});

和:

<a rel='{"gallery": "gal1", "smallimage": "images/image1.jpg","largeimage": "images/image1.jpg"}'>
    <img src = "images/image1.jpg" >
</a>

SAMPLE

于 2013-03-06T17:16:37.040 回答