Javascript 转义输出字符串并避免 NaN
尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,您的字符串连接中似乎有一个额外的
+
(就在带括号的三元运算符之前),这会导致您使用三元运算符的部分从字符串转换为数字因为额外的+
将被解释为一元加运算符,导致 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 whengroup
has a hyphen, and actually only havinggroup
appearing as NaN, not the entire ternary expression), I can't see how your code example would work correctly without removing the extra+
there