javascript jQuery 可以解析存储在变量中的 HTML 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5951988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:55:32  来源:igfitidea点击:

Can jQuery Parse HTML Stored in a Variable?

javascriptjqueryajax

提问by jake

I'm using PHP and an ajax command to take the entire HTML contents of an external web page (via the PHP file_get_contents()command) and passing that HTML into a javascript variable. Once I have the page's HTML contents stored in a variable, can I use jQuery to interact with the contents of that variable, in the same way that jQuery normally interacts with the DOM? In this example, I am trying to search for the existence of certain HTML elements (<div>and <script>tags) with specific ID attributes. Can anyone suggest how I can accomplish this?

我正在使用 PHP 和一个 ajax 命令来获取外部网页的整个 HTML 内容(通过 PHPfile_get_contents()命令)并将该 HTML 传递到一个 javascript 变量中。一旦我将页面的 HTML 内容存储在一个变量中,我是否可以使用 jQuery 与该变量的内容进行交互,就像 jQuery 通常与 DOM 交互的方式一样?在这个例子中,我试图搜索具有特定 ID 属性的某些 HTML 元素(<div><script>标签)的存在。谁能建议我如何做到这一点?

回答by BoltClock

If I understand you correctly, you should be able to just pass the variable to the jQuery function and work accordingly.

如果我理解正确,您应该能够将变量传递给 jQuery 函数并进行相应的工作。

A quick example with .filter():

一个简单的例子.filter()

$(myHtml).filter('#someid').doStuff();

回答by Quentin

Just pass it as a string to the jQuery constructor.

只需将它作为字符串传递给 jQuery 构造函数。

var foo = jQuery('<p><b>asd</b><i>test</i></p>').
alert(foo.find('i').text());

回答by Kshitij Saxena -KJ-

You can even use native JS to do this. In this case, add the new HTML to a hidden div by using its innerHTML property like this:

您甚至可以使用本机 JS 来执行此操作。在这种情况下,使用其 innerHTML 属性将新 HTML 添加到隐藏的 div 中,如下所示:

document.getElementById('hidden_div_id').innerHTML = myHTML;

Once the new HTML is added, you can walk through nodes using whatever methods you want.

添加新的 HTML 后,您可以使用任何您想要的方法遍历节点。

回答by UpHelix

Just inject it into a hidden div and manipulate what you need from it in there.

只需将它注入一个隐藏的 div 并在那里操作你需要的东西。

var myHTML;//variable with html from php

var $hiddenDIV = $('<div></div>').hide().appendTo('body').html(myHTML);
/*Now you can traverse the contents of $hiddenDIV.
 * If you need to get the contents back:
 */ 
var newHTML = $hiddenDIV.html();

回答by kkszysiu

Yes. And even if that is not available you could make an invisible div and then parse it there.

是的。即使那不可用,您也可以制作一个不可见的 div,然后在那里解析它。