[英]How to split array or assign key , jquery
Using Jquery , 使用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/ 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. 请注意,上述数组由jquery的imagesLoaded插件返回给我,并且我不能直接选择父类,因为它不在结果之内,ZI必须通过element.parent()获得任何帮助。 thnx!
谢谢!
Given the following HTML: 鉴于以下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: 还有一个仅捕获这些元素的jQuery选择器,在这种情况下,简单地是:
var my_array = $('a');
You would do: 您可以这样做:
$.each(my_array, function(i, el) {
el.href = $(el).children('img').attr('src');
});
If your selector is on the img
tags: 如果您的选择器位于
img
标签上:
var my_array = $('img');
You would do: 您可以这样做:
$.each(my_array, function(i, el) {
$(el).parent().attr('href', el.src);
});
Select the img elements. 选择img元素。
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.
在attr之后,因为这是一种方法。 Also, you need to do
$(this)
, since this
in the loop is a dom element, not a jquery object. 另外,您需要执行
$(this)
,因为循环中的this
是dom元素,而不是jquery对象。
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'));
});
});
if your code is: http://jsfiddle.net/ZZVXf/6/ then you just need to change it to: 如果您的代码是: http : //jsfiddle.net/ZZVXf/6/,则只需将其更改为:
$.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). 因为您想访问jQuery方法,所以需要用jQuery包装它(witch是DOM引用,而不是jQuery引用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.