Copy an atrribute value from one attribute to an inner string within the other
I have an <A>
tag, in which I need to copy the value of the HREF
attribute to an inner string within the REL
attribute. To be specific:
<a href="XX-some-link-XX" class="cloud-zoom-gallery small"
rel="useZoom开发者_开发知识库: 'zoom1', smallimage: 'XX-this-is-where-i-want-to-copy-that-link-XX'">
<img />
</a>
I've been able to partly achieve this by doing the following:
jQuery(document).ready(function() {
jQuery(".small").each(function() {
var src = jQuery(this).attr('href');
var a = jQuery(this).attr('rel', src);
});
});
But that removes the other data within the REL
attribute (e.g useZoom
).
So my question is - how to copy an attr value and paste it within a specific sting in the value of another attribute?
Too bad your rel
isn't a well-formed JSON object, or you could use JSON.parse()
to do the work.
This is probably cumbersome, but it's pretty generalizable.
$(function() {
var $jq = $("a:eq(0)");
var j = relParser($jq.attr("rel"));
j["smallimage"] = $jq.attr("href");
$jq.attr("rel",relBuilder(j));
alert(relBuilder(j));
})
function relBuilder(obj) {
var arr = [];
for (attr in obj) {
arr.push(attr+": '"+obj[attr]+"'");
}
return arr.join(", ");
}
function relParser(str) {
var arr = str.split(",");
var obj = {};
for (var i=0; i<arr.length; i++) {
var tmp = arr[i].split(":");
obj[tmp[0].trim()] = tmp[1].trim();
}
return obj;
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
here is the example to appending at the end:
jQuery(document).ready(function() {
jQuery(".small").each(function() {
var $this = $(this);
$this.attr('rel', $this.attr('rel') + " " + $this.attr('src'));
});
});
if you will need to more specific - you need to format value as you need. Like a simple strings in javascript.
Feel free to get the attribute value as a string an modify it before putting to the rel
attribute.
What Samich is saying is something like this (I won't tested but may works):
jQuery(document).ready(function() {
jQuery(".small").each(function() {
var src = jQuery(this).attr('href');
var rel = jQuery(this).attr('rel');
result = rel + src;
var a = jQuery(this).attr('rel', result);
});
});
If you haven't added smallimage:
as an attribute in your a
s yet, you could do this
html
<a href="XX-some-link-XX" class="cloud-zoom-gallery small"
rel="useZoom: 'zoom1'">
<img />
</a>
js
$('.small').each(function(){
var a = $(this).attr('href');
var rel = $(this).attr('rel');
$(this).attr("rel", rel + ", smallimage: '" + a + "'");
});
Example: http://jsfiddle.net/jasongennaro/a9BRz/
You will need to use the inspect element on the result panel to see how it works
精彩评论