jQuery 在 HTML 字符串中查找元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13413399/
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
Find element at HTML string
提问by Michael Z
Let's suppose I have
让我们假设我有
var testHTML = "<div id='demo_div'></div>";
I want to get above divas JQuery object to manipulate with it. I try to find it with:
我想在div之上作为 JQuery 对象来操作它。我尝试通过以下方式找到它:
var found = $(testHTML).find("#demo_div");
and with:
与:
var found = $(testHTML).find("div");
Both without luck. I have empty foundvariable. What am I do wrong?
两者都没有运气。我有空的发现变量。我做错了什么?
P.S.Yes I know I can have direct access to my divwith
PS是的,我知道我可以直接进入我的div与
$("#demo_div")
but I can't do it in my case - I need to get it from plain HTML that will be assigned to some variable just like in my example with testHTMLvar.
但在我的情况下我不能这样做 - 我需要从纯 HTML 中获取它,这些 HTML 将被分配给某个变量,就像在我的testHTMLvar示例中一样。
UPDATE:Even if I have not root divelement like here:
更新:即使我没有像这里这样的根div元素:
var testHTML = "<html><div id='demo_div'></div></html>";
I can't use findfor navigating divelement.
我不能使用find来导航div元素。
回答by James Allardice
The problem is that your div
is the root element in the collection, so you need to use .filter()
instead of .find()
(which only looks at descendant elements):
问题是你div
是集合中的根元素,所以你需要使用.filter()
而不是.find()
(它只查看后代元素):
var found = $(testHTML).filter("#demo_div");
I'm assuming your actual HTML string is more complex than the one in the question, otherwise you don't need to do anything other than $(testHTML)
and you will have a jQuery object containing that single element.
我假设您的实际 HTML 字符串比问题中的字符串更复杂,否则您无需执行任何操作,$(testHTML)
并且您将拥有一个包含该单个元素的 jQuery 对象。