gpt4 book ai didi

javascript - jQuery 迁移插件不允许我使用 jQuery(htmlString)

转载 作者:行者123 更新时间:2023-11-30 21:05:19 27 4
gpt4 key购买 nike

我正在努力升级一些使用 jQuery 1.7.2 版的旧软件。由于添加了一些新插件并且需要更新版本的 jQuery,我已将其升级到版本 1.12.1。

然而,有大量使用 jQuery(htmlString) 格式的 jQuery,例如:

  var html = $("<div>");

// Prepare the <div> of comments
$.each(data.comments, function() {
console.log(this);
html.append(
$("<div>").attr("class", "comment").html(
$("<div>").attr("class", "comment-profile-pic").html("").after(
$("<div>").attr("class", "comment-text").html(
$("<h1>").html(
this.full_name + " at " + this.started_datetime
).after(
$("<p>" + this.text + "</p>")
)
)
)
)
);
});

$(htmlString) 似乎在 1.9 版中贬值了,请阅读 https://jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring 上的升级指南它指出用于识别是否将 html 传递到选择器的格式已更改但是它还说:

When the jQuery Migrate plugin is used, it will use the old rules for determining if the string passed to $() "looks like HTML".

我已经附上了 jQuery 迁移插件版本 1.4.1,但它似乎没有任何区别,仍然无法识别选择器中的 HTML。

编辑:我尝试将 jQuery 恢复到 1.8.0 版,它按预期工作,但随后 1.9.0 版破坏了它。这意味着升级到 v 1.9 肯定是一个问题。

此外,在进行进一步测试后,我意识到当您执行类似 $("<div>").attr("class", "comment") 的操作时,将 html 传递给选择器确实有效。但如上例所示嵌套时不起作用。

有没有人知道如何在不重写将 HTML 传递到选择器的所有代码的情况下解决这个问题?

最佳答案

如果您阅读升级指南,您会发现只有当 html 字符串< 开头时才会出现问题。字符:

As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior. If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup.

也就是说,您应该使用 addClass() , 不是 attr('class', 'foo') , 你真的不应该将 jQuery 对象传递给 html()方法。如果您检查 documentation您会看到它接受 HTML 字符串或函数。

您应该改用其中一种元素插入方法,例如 append() , insert() , insertBefore()等等,像这样:

var data = {
comments: [{
text: 'foo1',
full_name: 'name1',
started_datetime: 'started1'
},{
text: 'foo2',
full_name: 'name2',
started_datetime: 'started2'
}]
}

var $parent = $("<div>").appendTo('body');

$.each(data.comments, function() {
var $comment = $("<div>").addClass('comment').appendTo($parent);
var $profilePic = $("<div>").addClass('comment-profile-pic').appendTo($comment);
$("<div>").addClass('comment-text').html(`<h1>${this.full_name} at ${this.started_datetime}</h1><p>${this.text}</p>`).insertAfter($profilePic);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - jQuery 迁移插件不允许我使用 jQuery(htmlString),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46692942/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com