正确的方法将html解析为jQuery对象 [英] The right way parse html to jQuery object

查看:86
本文介绍了正确的方法将html解析为jQuery对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个html字符串解析为jQuery对象,然后按ID找到一个元素。

I want to parse a html string to jQuery object then find an element by ID.

我尝试了3种方法,但只有最后一种方法。我不知道为什么其他人不起作用?

I tried 3 ways bellow, but only the last works. I don't know why the others not works?

var html = "<html><body><div id='main'></div></body></html>";

// Not work, return 0
console.log($(html).find('#main').length); 
// Not work, return 0
console.log($($.parseHTML(html)).find('#main').length); 
// Works, return 1
console.log($("<html/>").html(html).find('#main').length); 

以下是样本:
http://jsfiddle.net/nbyofkam/2/

推荐答案

记录


传递复杂的HTML时,某些浏览器可能无法生成完全复制所提供的HTML源的DOM。如上所述,jQuery使用浏览器的.innerHTML属性来解析传递的HTML并将其插入到当前文档中。在此过程中,某些浏览器会过滤掉某些元素,例如< html> < title> < head> 元素。因此,插入的元素可能无法代表传递的原始字符串。

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser"s .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

因此, $(html)减少为< div id =main>< / div>。您可以通过记录来验证$(html)[0] .outerHTML

As a result, $(html) is reduced to "<div id="main"></div>". You can verify that by logging $(html)[0].outerHTML.

所以你不能使用 find 没有包装它,这就是你所做的。

So you can't use find without wrapping it, which is what you do.

这篇关于正确的方法将html解析为jQuery对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆