2013-07-16 39 views
0
var theHTML = '<html><head><title>Hi</title><link rel="apple-icon-touch-precomposed" href="icon.jpg" /></head><body></body></html>'; 
alert($(theHTML).find('link[rel="apple-icon-touch-precomposed"]').attr('href')); 

它警告「未定義」。我希望它返回「icon.jpg」。哪裏不對?帶有字符串對象不工作的jQuery選擇器

+1

瀏覽器將會以不同的方式對待它。有些人會剝奪一些外部因素。 –

回答

3

試試這個:

alert($(theHTML).filter('link[rel="apple-icon-touch-precomposed"]').attr('href')); 

也就是說,用.filter()代替.find()

演示:http://jsfiddle.net/WmwRU/

如果你做一個console.log($(theHTML)),你就會明白爲什麼。

0

我不確定你是否可以這樣使用.find,我必須閱讀關於它的API。但是,您可以嘗試.prop('href')而不是.attr('href')。如果不工作,我也建議使用*=link[rel=*"apple-icon-touch-precomposed"]

1

我不知道你想要什麼,對,但是如果你使用的filter()代替find()它會工作,只要你想:

var theHTML = '<html><head><title>Hi</title><link rel="apple-icon-touch-precomposed" href="icon.jpg" /></head><body></body></html>'; 
alert($(theHTML).filter('link[rel="apple-icon-touch-precomposed"]').attr('href')); 

JSFiddle Demo