gpt4 book ai didi

javascript - 未附加 jQuery json 值

转载 作者:行者123 更新时间:2023-11-29 22:09:30 25 4
gpt4 key购买 nike

这是我的代码:

        success: function (data) {
var jsonData = $.parseJSON(data);
console.log("done");
$.each(jsonData, function(key, value) {
if (value !== "") { console.log("working on " + "#"+key+".div")
$("#"+key+".div").append("<pre>"+value+"</pre>");
}
});
}

如您所见,这是成功回调函数的一个片段。

在应该将值附加到我提供的选择器之前,一切正常。但由于某种原因,没有添加任何内容。

console.log("working on " + "#"+key+".div")

已打印,所以我知道 if 语句不是问题。

我认为错误在于这一行:

$("#"+key+".div").append("<pre>"+value+"</pre>"); 

但我无法说出我到底错过了什么。

示例 HTML:

<div id="prx1.sjc.div"></div>
<div id="prx2.sjc.div"></div>
<div id="sh1.sjc.div"></div>
<div id="sh2.sjc.div"></div>
<div id="sh3.sjc.div"></div>
<div id="sh4.sjc.div"></div>
<div id="sh5.sjc.div"></div>
<div id="sh6.sjc.div"></div>

最佳答案

在 id(或类)属性中使用点不是一个好的做法。

如果你想像这样引用一个id:

<div id="sh6.sjc.div"></div>

你必须以这种方式转义点

$("#sh6\\.sjc\\.div")

点保留在selector syntax中.在链接引用中写道:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").

在不转义点的情况下,您将选择一个 ID 为“sh6”的对象,它有两个类“sjc”和“div”,类似于

<div id="sh6" class="sjc div"></div>

快捷方式

转义 jquery 选择器的一个有趣的快捷方式在 article 中。 jQuery 博客。

检查选择器

当你处理这个问题时,检查选择器是否匹配一些元素,使用像

console.log("Matching the id sh6.sjc.div, occurrences:"+$("#sh6\.sjc\.div").length);

更容易验证您正在使用的选择器的正确性

关于javascript - 未附加 jQuery json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18814674/

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