簡體   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