简体   繁体   English

将字符串转换为jQuery对象并选择内部元素

[英]Convert string into jQuery object and select inner element

I wonder if there is a way to convert string into jQuery object and select inner elements without injecting the whole string into DOM and manipulate it in there. 我想知道是否有办法将字符串转换为jQuery对象并选择内部元素而不将整个字符串注入DOM并在那里操作它。 Thanks. 谢谢。

If possible, please give me example of converting 如果可能的话,请给我转换的例子

<div id=a1></div>
<div id=a3></div>

And select a1 from the object variable. 并从对象变量中选择a1。

这将从html创建元素并找到a1元素:

var element = $('<div id="a1"></div><div id="a3"></div>').filter('#a1').get(0);

The correct way to do this is: 正确的方法是:

var a1 = $('<div id="a1"></div><div id="a3"></div>').filter('#a1')[0];

Getting the DOM element out with [0] is equivalent to .get(0) . 使用[0]获取DOM元素相当于.get(0)

Update: interesting, I've never come across this corner case before but this: 更新:有趣的是,我从来没有遇到过这个角落,但是这个:

var a1 = $("#a1", "<div id=a1><//div><div id=a3><//div>")[0];

doesn't work when the element is at the top level , which I consider to be a bug. 当元素处于顶层时 ,它不起作用 ,我认为这是一个错误。 I've never come across that before so I thought I'd leave it up here as a cautionary tale. 我之前从未遇到过这种情况所以我以为我会把它留在这里作为一个警示故事。 Thanks to Crescent Fresh for pointing that out. 感谢Crescent Fresh指出这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM