繁体   English   中英

jQuery load()函数里面的范围

[英]Scope inside jQuery load() function

我的范围有问题。 抱歉这个noobish问题。

我试图用jQuery将图像附加到父div,但不知道如何将变量“theParent”传递给加载函数。

// 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'); 会工作,但使用:

var img = $("<img />", {
          "src"   : '/images/favicon.png',
          "class" : 'myClass'
      })
      .error(function(){ console.log('error'); })
      .load(function(){
                img.appendTo( theParent ); 
      });

尝试这个:

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" />')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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