0

使用 jQuery ,

我有一个数组结果

[<a href=""><img src="image1"></a>,<a href=""><img src="image2"></a>]

如果我尝试做每一个,我只会得到数组中的第一个,

我怎么能分开这个所以我可以做

$.each(my_array, function (index, value) {
     this.parent().attr.('href',this.src);// assign image as href to parent
});

这是不好的尝试

http://jsfiddle.net/ZZVXf/6/

请注意,上面的数组是由 jquery 的 imagesLoaded 插件返回给我的,我无法直接选择父级,因为它不在结果中,ZI 必须通过 element.parent() 任何帮助表示赞赏。谢谢!

4

5 回答 5

2
于 2012-06-21T06:30:06.760 回答
1

Select the img elements.

var $imgs = $("a > img");

Loop over selected elements

$imgs.each(function () {
    $(this).parent().attr('href',this.src);// assign image as href to parent
});

Note there is no '.' after attr, since that is a method. Also, you need to do $(this), since this in the loop is a dom element, not a jquery object.

于 2012-06-21T06:34:12.513 回答
0
var arr = ['<a href=""><img src="image1"></a>','<a href=""><img src="image2"></a>'];

$.each(arr, function (index, value) {
    alert(value.replace(/^.*src="(.*)".*$/m, '$1'));
});
于 2012-06-21T06:27:11.647 回答
0

Use this :

var obj = ['<a href=""><img src="image1"></a>,<a href=""><img src="image2"></a>']

jQuery(obj).each(function(key,value){
    var imgObj = jQuery(value).find('img')
       jQuery(imgObj ).each(function(key,value){ 
            jQuery(this).parent('a').attr('href',jQuery(this).attr('src')); 
     });
});​

Here is the DEMO

于 2012-06-21T06:37:05.997 回答
0

if your code is: http://jsfiddle.net/ZZVXf/6/ then you just need to change it to:

$.each($('img'), function (index, value) {
    $(this).parent().attr('href', this.src);// assign image as href to parent
});

because you want to access the jQuery methods you need to wrap this with jQuery (witch is the DOM reference, not a jQuery reference).

于 2012-06-21T06:38:23.370 回答