Javascript 转义输出字符串并避免 NaN

发布于 2024-12-22 21:52:51 字数 741 浏览 1 评论 0原文

尝试使用 jquery 输出包含连字符的字符串,如下所示: $("#OpsContent").html($("#OpsContent").html() + "" + $(this).text() +
+ ( ( group ) ? " for " + group + "" : "" )
+ " to
" + Choices + "
");

不幸的是,如果字符串“group”包含连字符,则输出始终显示为:
设置组排名NaN 5

我似乎无法将组变量正确解释为字符串,看起来更像是试图减去字符串的两半。我尝试在有问题的行之前使用 group = group.replace("-", ".");"\-" ,但它没有帮助。更奇怪的是,紧随其后的一行工作正常:

OpsPending[ count ] = "?do=" + String($(this).attr("id"))
+ "&selection=" + 选择
+ ( ( 组 ) ? "&group=" + 组 : "" );

完美地输出到变量!

一个解决方案是返回并用 php 预处理页面中的所有连字符,但这似乎不必要地复杂:应该有比这更好的方法。

Trying to use jquery to output a string that contains a hyphen like so:
$("#OpsContent").html($("#OpsContent").html() + "<b>" + $(this).text() +
+ ( ( group ) ? " for <u>" + group + "</u>" : "" )
+ " to</b> " + choices + "<br />");

Unfortunately if the string "group" contains a hyphen, the output always appears as:
<b>Set Group Rank<u>NaN</u> to</b> 5

I can't seem to get the group variable to be correctly interpretted as a string, it seems rather like it is trying to subtract the two halves of the string. I have tried using group = group.replace("-", "."); and "\-" before the line in question, but it doesn't help. Even stranger is the fact that a line immediately after works fine:

OpsPending[ count ] = "?do=" + String($(this).attr("id"))
+ "&selection=" + choices
+ ( ( group ) ? "&group=" + group : "" );

outputs to the variable perfectly well!

A solution would be to go back and pre-process all the hyphens in the page with php, but that seems unnecessarily complicated: there should be a better way than this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不疑不惑不回忆 2024-12-29 21:52:51

嗯,您的字符串连接中似乎有一个额外的 + (就在带括号的三元运算符之前),这会导致您使用三元运算符的部分从字符串转换为数字因为额外的 + 将被解释为一元加运算符,导致 NaN。虽然这并不能完全解释你的症状(即它仅在 group 有连字符时发生,并且实际上只有 group 显示为 NaN,而不是整个三元表达式),如果不删除额外的 + ,我无法看到您的代码示例如何正常工作

Hm, you seem to have an extra + in your string concatenation (right before the parenthesized ternary operator), which would cause the part where you are using the ternary operator to be converted from a string to a number since that extra + would be interpreted as a unary plus operator, resulting in NaN. Although that doesn't exactly explain your symptons (i.e. it only occuring when group has a hyphen, and actually only having group appearing as NaN, not the entire ternary expression), I can't see how your code example would work correctly without removing the extra + there

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文