11

当单击类 numObj 的元素时,我想显示一个文本框。出于某种原因,我得到 NaNNaNaNaNNaNNaNaNaN ,我希望在下面的代码中看到 searchForm 变量的结果。

我知道 NaN 代表 Not a Number。我不明白的是为什么 Javascript 需要一个数字?我不明白为什么它在乎。

$(".numObj").live('click',function(){
   var preId = $(this).attr('preId');
   var arrayPos = $(this).attr('numArrayPos');

        alert(preId +" "+arrayPos);

        var searchForm = "<table border='0' cellspacing='0' cellpadding='4' id='add-tag2'>"+
          +"<tr class='normal'><td bgcolor='#EEEEEE' valign='bottom' nowrap='nowrap'><span class='normal-small'>"+
          +"<input name='predicate-name2' type='text' class='normal' id='predicate-name2' size='4' />"+
          +"</span></td>"+
          +"<td bgcolor='#EEEEEE' valign='bottom' nowrap='nowrap'><span class='normal-small'>&lt;=</span></td>"+
          +"<td bgcolor='#EEEEEE' valign='bottom' nowrap='nowrap'>x</td>"+
          +"<td valign='bottom' bgcolor='#EEEEEE'>&lt;=</td>"+
          +"<td valign='bottom' bgcolor='#EEEEEE'><span class='normal-small'>"+
          +"<input type='text' name='object-object2' id='object-object2' class='normal' size='4' />"+
          +"</span></td>"+
          +"</tr>"+
          +"</table>";
        $(".numObj").filter("[preId='"+preId+"']").filter("[numArrayPos='"+arrayPos+"']").html(searchForm);

    }); 

生成的具有 numObj 类的代码如下所示

<td><div class="numObj" preid="73" numarraypos="5"><span class="normal">585.0</span></div></td>
4

4 回答 4

20

正如其他人指出的那样,问题在于+操作员。除了连接字符串外,它还用作数学加法。由于 Javascript 的动态类型,+在字符串上单独使用一元将导致字符串转换为数字:

+"12"; // -> 12
+"10" + +"12" // -> 22

代码的几行在行尾和新行的开头+都有运算符。第二个将被视为一元数学加法,并将尝试将字符串转换为数字。考虑以下:+

"Hello" +
+ "World" // -> "HelloNaN" 
于 2010-05-27T10:54:05.653 回答
11

您有多个彼此相邻的加号运算符。

var searchForm = "<table border='0' cellspacing='0' cellpadding='4' id='add-tag2'>"+
+"<tr class='normal'><td bgcolor='#EEEEEE' valign='bottom' nowrap='nowrap'><span class='normal-small'>"+

请注意,第一行末尾有一个加号运算符,最后一行开头有一个。删除其中一个加号运算符(对于每一行),您可能会摆脱错误。

顺便说一句,JSLint 很快就发现了这些错误。

于 2010-05-27T10:45:15.037 回答
4

将每行末尾的 + 符号去掉var searchForm

var searchForm = "<table border='0' cellspacing='0' cellpadding='4' id='add-tag2'>"
      +"<tr class='normal'><td bgcolor='#EEEEEE' valign='bottom' nowrap='nowrap'><span class='normal-small'>"
      +"<input name='predicate-name2' type='text' class='normal' id='predicate-name2' size='4' />"
      +"</span></td>"
      +"<td bgcolor='#EEEEEE' valign='bottom' nowrap='nowrap'><span class='normal-small'>&lt;=</span></td>"
      +"<td bgcolor='#EEEEEE' valign='bottom' nowrap='nowrap'>x</td>"
      +"<td valign='bottom' bgcolor='#EEEEEE'>&lt;=</td>"
      +"<td valign='bottom' bgcolor='#EEEEEE'><span class='normal-small'>"
      +"<input type='text' name='object-object2' id='object-object2' class='normal' size='4' />"
      +"</span></td>"
      +"</tr>"
      +"</table>";
于 2010-05-27T10:47:18.807 回答
0

使整个 searchForm 变量仅存在于一行中使其工作......但这并不优雅。如果有更好的解决方案,我很想知道。

于 2010-05-27T10:47:27.323 回答