jQuery() 在 jQuery.parseHTML() 结果中找不到元素

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

jQuery() not finding elements in jQuery.parseHTML() result

javascriptjquery

提问by Dmitry Minkovsky

I'm writing tests with QUnit and using $.ajax()to pull in HTML for some of the tests from the the dev site running on my local:

我正在使用 QUnit 编写测试,并$.ajax()用于从本地运行的开发站点中提取一些测试的 HTML:

add_elements = function(location, selector) { 
  $.ajax(location, {async: false}).done(function(data) {
    stor.$els = $(selector, $.parseHTML(data));
    stor.$els.appendTo($('body'));
  })
}

Using this function at a certain location, I get the following datapassed to my .done()callback:

在某个位置使用此函数,我将以下内容data传递给我的.done()回调:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Home</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/static/css/bootstrap.min.css" rel="stylesheet" media="screen">

</head>

<body>
<div id="app-container" class="container-fluid">
    <div class="page-header">
        <h1>
            <a href="/">Home</a>
            <small>Text</small>
        </h1>
    </div>

    <div id="hero-units" class="carousel-inner slide">

        <div class="hero-unit home item active">
            <h1>
                Text text text
            </h1>
            <p>
                More text!
            </p>
            <div id="app-nav">
                <a id="lets-go" class="btn btn-primary btn-large nav-forward" href="/what-up/">
                    Let's go
                </a>
            </div>
        </div>

    </div>
</div>

<script src="/static/js/jquery.js"></script>
<script src="/static/js/underscore.js"></script>
<script src="/static/js/backbone.js"></script>
<script src="/static/js/bootstrap.js"></script>
<script src="/static/js/site-fiddle.js"></script>
<script src="/static/js/site.js"></script>

</body>
</html>

Everything works if selectoris #hero-unitsor .hero-unit, but $(selector, $.parseHTML(data))returns nothing if selectoris #app-container! And I want a jQueryobject for the div#app-containerelement.

如果selector#hero-units.hero-unit,则一切正常,但如果是,则不$(selector, $.parseHTML(data))返回任何selector内容#app-container!我想要一个元素的jQuery对象div#app-container

And here is what kills me:

这就是杀死我的原因:

  • $.parseHTML(data)doescontain the div#app-containerelement. It's just $.parseHTML(data)[7].
  • Yet, $('#app-container', $.parseHTML(data))is an empty array.
  • $('div', $.parseHTML(data))includes all the divs inside of div#app-container, but not div#app-containeritself.
  • $.parseHTML(data)确实包含div#app-container元素。这只是$.parseHTML(data)[7]
  • 然而,$('#app-container', $.parseHTML(data))是一个空数组。
  • $('div', $.parseHTML(data))包括 中的所有divs div#app-container,但不包括div#app-container其本身。

What's going on here? It appears that what's happening is that $is not looking at any of the top-level elements returned by $.parseHTML(data)or $($.parseHTML(data))), and just their children.

这里发生了什么?看起来发生的事情是$没有查看$.parseHTML(data)or返回的任何顶级元素$($.parseHTML(data))),而只是查看它们的子元素。

How can I get a jQueryobject for div#app-containerfrom this $.parseHTML(data)?

我怎样才能得到一个jQuery为对象div#app-container,从这个$.parseHTML(data)

ANSWER

回答

The $(selector, $.parseHTML(data))-style lookup uses $.find. Since I'm looking for an element that's top-level in this jQuery object, I should use $.filterinstead. Voila.

$(selector, $.parseHTML(data))式的查找使用$.find。因为我正在寻找这个 jQuery 对象中的顶级元素,所以我应该使用它$.filter。瞧。

回答by Amy

You need to create a DOM element to append the results of .parseHTML()first so that it creates a DOM tree before jQuery can traverse it and find div#app-container.

您需要创建一个 DOM 元素来附加.parseHTML()first的结果,以便它在 jQuery 遍历它并找到 DOM 树之前创建一个 DOM 树div#app-container

var tempDom = $('<output>').append($.parseHTML(str));
var appContainer = $('#app-container', tempDom);

I used your example and got it working: http://jsfiddle.net/gEYgZ/

我使用了您的示例并使其正常工作:http: //jsfiddle.net/gEYgZ/

The .parseHTML()function seems to choke on the <script>tags, so I had to remove them.

.parseHTML()功能似乎在<script>标签上窒息,所以我不得不删除它们。

PS.Obviously <output>is not a real HTML tag, just using it for the example

附注。显然<output>不是真正的 HTML 标签,仅用于示例

回答by jcubic

You can try this:

你可以试试这个:

$($.parseHTML('<div><span id="foo">hello</span></div>')).find('#foo');

for strings that start with <you can shorter that code to just:

对于以<您开头的字符串,您可以将该代码缩短为:

$('<div><span id="foo">hello</span></div>').find('#foo');

回答by adu

Just ran into this.

刚碰到这个。

Turns out $.parseHTMLreturns a vanilla Arrayof DOM elements, and that doesn't support the jQuery find that you want.

结果$.parseHTML返回了一个ArrayDOM 元素的香草,并且不支持您想要的 jQuery find。

I think this is the cleanest solution for converting an HTML string to a jQuery object:

我认为这是将 HTML 字符串转换为 jQuery 对象的最干净的解决方案:

var html = '<div><span id="foo">hello</span></div>';
var $foo = $(html).find('#foo');

Note: You may want to use $.trimaround your html strings so jQuery doesn't get confused by whitespaces.

注意:您可能希望$.trim在 html 字符串周围使用,这样 jQuery 就不会被空格混淆。

回答by Robert Moskal

It doesn't have anything to do with the html not being part of the DOM. It's just that for whatever reason the top level tag(s) in the parsed HTML cannot be found. If the element you are looking for is wrapped in another tag, then the find works as you expect. BTW, wrapping the element in the body tag won't work, but all the others I have tried work fine.

它与不属于 DOM 的 html 没有任何关系。只是由于某种原因无法找到解析的 HTML 中的顶级标签。如果您要查找的元素包含在另一个标签中,那么查找将按您的预期工作。顺便说一句,将元素包装在 body 标签中是行不通的,但我尝试过的所有其他元素都可以正常工作。

var bad = $.parseHTML('<ul><<li><one/li>/<li>two</li></ul>');
console.log($(bad).find('li').length);  //will be 2
console.log($(bad).find('ul').length);  //will be 0 

var good = $.parseHTML('<div><ul><<li><one/li>/<li>two</li></ul></div>');
console.log($(good).find('li').length); //will be 2
console.log($(good).find('ul').length); //will be 1

This is definitely the case in jQuery 1.11, not sure what happens in later versions. Here is a fiddle that demonstrates: http://jsfiddle.net/ndnnhf94/

在 jQuery 1.11 中肯定是这种情况,不确定在以后的版本中会发生什么。这是一个演示的小提琴:http: //jsfiddle.net/ndnnhf94/

回答by Jeroen Verheyden

Above answers didn't work for me, this did:

以上答案对我不起作用,这对我有用:

use jQuery.parseHTML to parse the HTML into an array of elements; then you'll be able to convert it to a jQuery collectionand use filterto restrict the collection to elements matching a selector.

使用 jQuery.parseHTML 将 HTML 解析为元素数组;然后您就可以将其转换为 jQuery 集合使用过滤器将集合限制为与选择器匹配的元素。

var html =
'<td class="test">asd</td>' +
'<td class="last">jkl</td>';
var obj = $($.parseHTML(html)).filter('.test');

回答by Jai

i think you should try with this:

我认为你应该试试这个:

$('body', $.parseHTML(data))

回答by Stephon Lawrence

I believe this will work, especially if you specifically need to find the element by id;

我相信这会起作用,特别是如果您特别需要通过 id 查找元素;

function findInParsed(html, selector){
    return $(selector, html).get(0) || $(html).filter(selector).get(0);
}

If you need the jquery version of the object then you can get it with this

如果您需要对象的 jquery 版本,那么您可以使用它来获取它

function findInParsed(html, selector){
    var check = $(selector, html).get(0);
    if(check)
        return $(check);
    check = $(html).filter(selector).get(0)
    return (check)? $(check) : false;
}