2013-09-22 48 views
0

我有以下鏈接,應該顯示的鏈接內的圖像時加載的javascript:如何使用父錨的href設置圖像src?

<a href="http://upload.wikimedia.org/wikipedia/commons/a/ae/Mad_scientist.svg" id="a"> 
<img alt="no image"> 
</a> 

的JavaScript應該獲得鏈接的href屬性,並書面說明的HTML時包括它圖片。

$('#a').html('<img src="' + $(this).attr('href') + '">image'); 

不知何故,$(this).attr('href')將返回undefined。這有什麼問題?

JsFiddle

回答

4

DEMO

$('#a').html(function() { 
    return '<img src="' + $(this).attr('href') + '">image' 
}); 

函數返回的HTML內容進行設置。收到集合中元素的索引 位置和舊的HTML值爲 參數。 jQuery在調用函數之前清空元素;使用 oldhtml參數來引用先前的內容。在 函數中,這指的是集合中的當前元素。

Refrence

http://api.jquery.com/html/#html-functionindex--oldhtml

http://learn.jquery.com/javascript-101/this-keyword/

在你的代碼

$('#a').html('<img src="' + $(this).attr('href') + '">image'); 

$(this)在你的代碼是不明確的。

例如。

$('#a').html(function() { 
     return '<img src="' + $(this).attr('href') + '">image' 
}); 

在上面的代碼this指的是當前元素即元素與id="a"

+0

任何人都可以解釋它爲什麼要做這樣? –

+0

@QuestionOverflow耶確定更新答案在一分鐘內。 –

+0

啊..我看到它在'.html()'函數中說,'this'是指集合中的當前元素。謝謝! –

1
var obj= $("#a"); 
obj.html('<img src="' + obj.attr('href') + '">image'); 
+0

任何人都可以解釋爲什麼它必須這樣做? –

+0

,因爲這裏實例化爲什麼都沒有。 –

相關問題