I am having a problem with the scope. Sorry for this noobish question.
I am trying to append images to a parent div with jQuery, but don't know how to pass the variable "theParent" to the load function.
// inside a this.each loop
var theParent = $(this).parent('div.parent');
var img = $("<img />")
.attr('src', '/path/img.jpg')
.error(function(){ console.log('error'); })
.load(function(){
img.addClass('myClass'); // <-- not working plz help
theParent.append(img); // <-- not working plz help
});
$(this).addClass('myClass');
would work but use:
var img = $("<img />", {
"src" : '/images/favicon.png',
"class" : 'myClass'
})
.error(function(){ console.log('error'); })
.load(function(){
img.appendTo( theParent );
});
Try this:
var theParent = $(this).parent('div.parent');
var img = $("<img />", {
src: '/path/img.jpg',
"class": 'myClass'
}).appendTo(theParent);
根据http://api.jquery.com/load-event/“this ”是load事件所附加的对象。
您是否尝试过以下方法:
$('#theDiv').prepend('<img id="theImg" class="myClass" src="theImg.png" />')
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.