javascript - 使用 jQuery,IE<9 无法将元素束附加到文本节点。这是 jQuery 错误吗?

标签 javascript jquery html internet-explorer

在 jQuery 1.11.3 中,我发现元素在 IE<9 中是无序的,当我附加()一束包括文本节点的元素时。这是 jQuery 错误还是我的错误?

测试代码:

<!DOCTYPE html>
<html>
    <head>
        <title>jQuery test</title>
        <script src="http://code.jquery.com/jquery-1.11.3.js" charset="utf-8"></script>
    </head>
    <body>
        <div id="div"></div>
        <script>
            $('#div').append(
                $('<span/>', {
                    css: {
                        color: 'red'
                    },
                    text: 'Some'
                }).add(
                    $(document.createTextNode(' Texts '))
                ).add(
                    $('<span/>', {
                        css: {
                            fontSize: 'x-large'
                        },
                        text: 'are'
                    })
                ).add(
                    $(document.createTextNode(' appended.'))
                )
            );
        </script>
    </body>
</html>

在 IE 11(和所有其他现代浏览器)中:

IE11

在 IE 8 仿真模式下:

IE8

最佳答案

我认为这不是错误,而是记录在案的 jQuery 行为。直接来自doc for .add() :

Do not assume that this method appends the elements to the existing collection in the order they are passed to the .add() method. When all elements are members of the same document, the resulting collection from .add() will be sorted in document order; that is, in order of each element's appearance in the document. If the collection consists of elements from different documents or ones not in any document, the sort order is undefined.

因此,jQuery 专门记录了不在 DOM 中的新创建的 DOM 元素的顺序是未定义的。

正如我在评论中提到的,您可以通过使用此类构造而不是 .add() 自行控制 .append() 命令来避免此问题:

$(...).append(...).append(...).append(...)

jQuery 文档本身推荐:

$(array_of_DOM_elements) 

因此,您可以将 DOM 元素收集到一个数组中(而不是收集到一个 jQuery 对象中),这也比多次调用 .add()(每次调用都会创建一个新的jQuery 对象),然后在一次调用中将该数组添加到 jQuery 对象。

您还可以创建自己的文档片段,将元素追加到片段中,然后插入片段。

关于javascript - 使用 jQuery,IE<9 无法将元素束附加到文本节点。这是 jQuery 错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430461/

相关文章:

javascript - 如何为动态插入的 'input' 文本元素正确捕获 onchange 或 onkeyup 事件?

javascript - JSON 解析和安全

javascript - 从 handlebars 助手返回 html 对象

javascript - 使用查询从 div(page) 搜索文本第二次会崩溃

jquery - .on() 函数调用之间的区别

javascript - jQuery text() 返回不需要的字符

html - 960gs 的行排水沟

c# - 将数据传递到我的 View 时出错?

javascript - Moris 图表为条形图交替颜色

javascript - 将 <div> 转换为 <p>