简体   繁体   中英

How to split array or assign key , jquery

Using Jquery ,

I have an array result

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

if I try to do each I only get the first one in array ,

how could I split this so I could do

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

here is bad try

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

Please note that array above is returned to my by imagesLoaded plugin for jquery and I canot select parent directly since it is not within the result , ZI must go by element.parent() any help is appreciated. thnx!

Given the following HTML:

<a href=""><img src="image1"></a><a href=""><img src="image2"></a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

And a jQuery selector which catches only these elements, in this case simply:

var my_array = $('a');

You would do:

$.each(my_array, function(i, el) {
    el.href = $(el).children('img').attr('src');
});

Example


If your selector is on the img tags:

var my_array = $('img');

You would do:

$.each(my_array, function(i, el) {
    $(el).parent().attr('href', el.src);
});

Example

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.

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'));
});

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM