我将文本数据转换为jquery对象,但创建的文本数据不是我期望的

I converted text data to jquery object but the created one was not what I expected

本文关键字:数据 文本 创建 期望 对象 转换 jquery      更新时间:2023-09-26

我想将文本数据转换为jquery对象,并希望使用"find()"方法或"filter()"方法或jquery具有的其他方法。
但不知何故,转换后的jquery对象的innerHtml并不是我所期望的。
我想知道发生了什么。
http://jsfiddle.net/LxXtz/14/

<!DOCTYPE html>
<html>
<head>
    <script src="lib/jquery-2.0.3.min.js"></script>
    <style type="text/css">
    <!--
    #parts{
        display: none;
    }
    -->
    </style>
    <script>
        $(function () {
            $('#execution').on('click', function () {
                var parts = $('#parts').html(); //Parts is text data. I create the data from html just for this demo.
                var partsobj = $(parts); // Convert to jQuery object.
                console.log(partsobj.html()); // Why not be outputted innerHtml of #parts??
            });
        });
    </script>
</head>
<body>
<input type="button" id="execution" value="Execute" />
<div id="parts">
    <div id="div1">
        <div>This is in Div1</div>
    </div>
    <div id="div2">This is Div2</div>
</div>
</body>
</html>

你从$('#parts').html()下面得到

<div id="div1">
    <div>This is in Div1</div>
</div>
<div id="div2">This is Div2</div>

然后当你把它转换为jquery对象时,它会变成包含3个元素的数组,

Object[div#div1, <TextNode textContent="'n ">, div#div2]

因此,使用 .html() 只给出第一个元素 innerHTML。那是

<div>This is in Div1</div> 

检查此 http://jsfiddle.net/LxXtz/16/。检查控制台。

http://api.jquery.com/html/指出:

"说明:获取匹配元素集中第一个元素的 HTML 内容。"如果选择器表达式匹配多个元素,则只有第一个匹配项才会返回其 HTML 内容。

您的 partsobj 匹配 3 个条目;div, textnode,div.解决它的一种方法是循环使用它们。

partsobj.each(function(){
    if($(this).html())
        $('#result').text($('#result').text()+$(this).html())
})
var parts = $('#parts').children(); 
console.log(parts);

这将为您提供一个 HTML 元素数组。 如果你想要这些子元素的原始 html。

var parts = $('#parts').children(); 
$.each({parts, function() {
    console.log($(this).html());
});
所以

你想要 div#execution 的 html ,然后将其插入到 div#result 中。 如果要移动它,则

$('#execution').on('click', function () {
  $('#result').append($('#parts').html())
});

这是你的意思吗?