2013-04-08 63 views
1

我遇到了作用域問題。對於這個沒有問題的問題抱歉。jQuery中的作用域load()函數

我想將圖像追加到父div與jQuery,但不知道如何將變量「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 
        }); 
+1

你能張貼整個this.each循環?看起來像是等待.load在下一次迭代之前完成的問題。 – ZimSystem 2013-04-08 15:19:39

+0

這裏似乎沒有任何範圍問題。 – Quentin 2013-04-08 15:19:46

+0

這似乎工作正常 - http://jsfiddle.net/k2Kb7/1/(雖然不知道你的循環) – Ian 2013-04-08 15:38:32

回答

3

LIVE DEMO

$(this).addClass('myClass');會工作,但使用:

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

'img'未定義? 'load'回調會稍後執行,所以當它試圖在稍後解析對'img' **的引用時,它應該可用。 – Ian 2013-04-08 15:29:35

+0

謝謝,像一個魅力工作! – herrmarek 2013-04-08 15:30:10

0

試試這個:

var theParent = $(this).parent('div.parent'); 

    var img = $("<img />", { 
     src: '/path/img.jpg', 
     "class": 'myClass' 
    }).appendTo(theParent); 
0

你有沒有試過如下:

$('#theDiv').prepend('<img id="theImg" class="myClass" src="theImg.png" />')