Setting multiple attributes with .attr()
I'm having a function here:
EDIT : gave you full code here!
$(".thumbnail").live("click",
function(){
$('#imageBig').find("#pictureContainer").remove();
$('#loadingImage').fadeIn();
var path = $(this).children().attr("src");
var newPath = path.substring(0, path.length-9);
var newPath2 = newPath += ".jpg";
var imageLoad = new Image();
$(imageLoad).load(function () {
if (--imageLoad == 0) {
// ALL DONE!
}
// a开发者_StackOverflow中文版nything in this function will execute after the image loads
$('#loadingImage').fadeOut();
var newImg = $('<img />').attr('src',$(this).attr('src'));
newImg.css("height","400px").css("width","600px");
$('#imageBig').append( $(newImg) );
})
.attr({
src:newPath2,
id:"pictureContainer"
});
})
My problem is with the .attr()
When loading the image, it does change the src (so line 1 "src:newPath2
" works), but it doesn't put the id. So when my image is created, it only does : <img src="newpath2" />
. No id. Am I doing something wrong? I checked the jquery documentation a few times and i'm pretty sure that's how to do it.
I think the problem comes with the .load() but i'm not sure what doesn't work.
Thank you!
(if you need it, I can give you the code before that)
SOLVED :
Just have to give the id to newImg instead of imageLoad.
newImg has the same SRC because of $('<img />').attr('src',$(this).attr('src'))
, but not the same ID, then I think you are appending (and referring to) newImg, so you should give the ID to newImg instead of loadImage.
Setter and Getter!
(function($) {
// Attrs
$.fn.attrs = function(attrs) {
var t = $(this);
if (attrs) {
// Set attributes
t.each(function(i, e) {
var j = $(e);
// Aplica atributos
for (var attr in attrs) {
j.attr(attr, attrs[attr]);
};
});
return t;
} else {
// Get attributes
var a = {},
r = t.get(0);
if (r) {
r = r.attributes;
for (var i in r) {
var p = r[i];
if (typeof p.nodeValue !== 'undefined') a[p.nodeName] = p.nodeValue;
}
}
return a;
}
};
})(jQuery);
Use:
// Setter
$('#element').attrs({
'name' : 'newName',
'id' : 'newId',
'readonly': true
});
// Getter
var attrs = $('#element').attrs();
I might be a bit confused by what you are trying to do but why not just do:
var newImg = $('<img />').attr('src',$(this).attr('src')).attr('id',$(this).attr('id'));
Wouldn't that give you the id as well?
精彩评论