Javascript 如何使用jQuery选择变量中的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3622834/
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-08-23 05:27:58  来源:igfitidea点击:

How to select elements within a variable using jQuery?

javascriptjquery

提问by Fourjays

I'm trying to make a simple image browser for TinyMCE which I am using in my CMS. As part of this I need to detect whether the user has selected an existing image, so I can display the "edit" form instead of the "choose an image form".

我正在尝试为我在 CMS 中使用的 TinyMCE 制作一个简单的图像浏览器。作为其中的一部分,我需要检测用户是否选择了现有图像,因此我可以显示“编辑”表单而不是“选择图像表单”。

var selected_html = ed.selection.getContent();
var $elem = $(selected_html);
console.log($elem);

The first function returns the user selected text from the editor window as a string of HTML. I then would like to use jQuery (although plain javascript is just ok too) to check if this string contains an img tag before subsequently grabbing the src and title attributes for editing.

第一个函数将用户从编辑器窗口中选择的文本作为 HTML 字符串返回。然后我想使用 jQuery(虽然纯 javascript 也可以)在随后获取 src 和 title 属性进行编辑之前检查此字符串是否包含 img 标记。

Now I've got as far as getting the html to turn into an object. But after this I can't manage to search it for the img element. After reading this (How to manipulate HTML within a jQuery variable?) I tried:

现在我已经把 html 变成了一个对象。但在此之后,我无法设法搜索 img 元素。阅读本文后(如何在 jQuery 变量中操作 HTML?)我尝试过:

$elem.find('img');

But it just comes out as an "undefined" object...

但它只是作为一个“未定义”的对象出现......

I think I'm missing something fairly obvious here (it is getting late), but after an hour I still can't figure out how to grab the img tag from the selection. :(

我想我在这里遗漏了一些相当明显的东西(已经很晚了),但是一个小时后我仍然无法弄清楚如何从选择中获取 img 标签。:(

Many thanks in advance.

提前谢谢了。

回答by user113716

Because the <img>is at the root of the jQuery object, you need to use .filter()instead of .find().

因为<img>是 jQuery 对象的根,所以您需要使用.filter()代替.find()

$elem.filter('img');

The .filter()method looks at the element(s) at the top level of the jQuery object, while .find()looks for elements nestedin any of the top level elements.

.filter()方法查看 jQuery 对象顶层.find()的元素,同时查找嵌套在任何顶层元素中的元素。

If you're not sure beforehand where the target element will be, you could place the HTML into a wrapper <div>to search from. That way the HTML given will never be at the top.

如果您事先不确定目标元素的位置,您可以将 HTML 放入包装器中<div>进行搜索。这样给定的 HTML 永远不会出现在顶部。

var selected_html = ed.selection.getContent();
var $elem = $('<div>').html(selected_html);

var $img = $elem.find('img');

回答by Frankie

Try to see what is really inside your $elemvariable. Just do a console.log($elem)using both Firefoxand Firebugand you should be able to manage quite alright! ;)

试着看看你的$elem变量里面到底有什么。只需console.log($elem)同时使用FirefoxFirebug,您应该能够很好地管理!;)