带有字符串对象的jQuery选择器不起作用

jQuery selector with string object not working

本文关键字:jQuery 选择器 不起作用 对象 字符串      更新时间:2023-09-26
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'));

它提醒"未定义"。我希望它返回"图标.jpg"。怎么了?

试试这个:

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

也就是说,使用 .filter() 而不是 .find() .

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

如果你做一个console.log($(theHTML))你就会明白为什么。

这样的 HTML 上选择时,您需要使用.filter()而不是.find()

JSFiddle

我不知道

你想要它做什么,但如果你使用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

我不确定你是否可以这样使用.find,我必须阅读有关它的API。但是,您可以尝试.prop('href')而不是.attr('href')。如果这不起作用,我还建议在=后使用*,例如link[rel=*"apple-icon-touch-precomposed"]