【问题标题】:Adding integers on appending在追加时添加整数
【发布时间】:2013-01-17 07:34:46
【问题描述】:

请看下面的代码。我无法让我的价值观相加。数字只是将自身添加到字符串的后面。想知道有什么办法。

$("a[name='older_post']").click(function(){
    $("div.main_ads_div a[name='older_post']").remove().fadeOut();
    var last_td_id=parseInt($("table.main_ads_table:last").find("td.load_ads:last").attr("id"),10);
    alert(last_td_id);   //OUTPUTS 38
    $("div.main_ads_div").append('<table class="main_ads_table" col="7" row="7"><tr><td class="load_ads" id="'+last_td_id+1+'"></td><td class="load_ads" id="'+last_td_id+2+'"></td><td class="load_ads" id="'+last_td_id+3+'"></td><td class="load_ads priority" id="'+last_td_id+4+'"></td><td class="load_ads priority" id="'+last_td_id+5+'"></td><td class="load_ads" id="'+last_td_id+6+'"></td><td class="load_ads" id="'+last_td_id+7+'"></td><td class="load_ads" id="'+last_td_id+8+'"></td></tr></table>');
});

所以我想在这里得到的是每个附加的td,我试图得到39, 40, 41, 42...,但我得到的值是381, 382, 383,...等。

对这里的任何帮助表示赞赏。

【问题讨论】:

    标签: javascript jquery append parseint


    【解决方案1】:

    用括号括起来:

     ... + (last_td_id + 7) + ...
    

    【讨论】:

      【解决方案2】:

      你正在将字符串与数字连接起来,将加法括在括号中以对其进行算术运算。

      改变

      +last_td_id+1+
      

      +(last_td_id+1)+
      

      +association 是从左到右的,在语句 '....class="load_ads" id="'+last_td_id 首先将左侧字符串与数字 (last_td_id) 连接起来,并给出一个字符串,该字符串再次连接增量数字,例如 (2 或 3 ..) 到上一个字符串。将括号括在数字周围使其precedence 为高,首先执行计算并将结果连接到字符串中。

      【讨论】:

      • 不需要 parseInt - 它会先将数字转换为字符串
      • parseInt 已经包含在代码中:var last_td_id=parseInt( @Bergi:“它会先将数字转换为字符串”:你的意思是parseint 返回一个字符串?这条线有点令人困惑,imo。
      • @Cerbrus:不,不是“返回”而是“预期”。请参阅spec algorithm 的第 1 步。
      • @Bergi:啊,所以输入参数首先被转换为字符串,如果它们还没有......这更有意义:P
      【解决方案3】:

      plus 运算符仅在两个操作数都是数字时才执行数学加法。如果其中一个是字符串,它将执行字符串连接(并将1 转换为"1")。

      然而它是left associative,你没有使用括号。所以你的表达式被评估为

      (((…('<…' + id) + 1) + '"…') + id) + 2) + …
      

      每一步都会产生一个字符串。正如其他人已经提到的那样,您需要通过将其包装在括号中来强制执行添加:

      '<…' + (id + 1) + '"…' + (id + 2) + …
      // evaluated as
      (((…('<…' + (id + 1)) + '"…') + (id + 2)) + …
      

      【讨论】:

        【解决方案4】:

        在 javascript 中使用“+”总是附加变量/字符串。试试这样的:

        var c = (16 * 24) + 12;
        d = c.toString();
        

        只有这样 var 'd' 才会给你数学输出

        在你的情况下,它可能是

        (last_td_id+4).toString();  and so on
        

        【讨论】:

        • console.log((16 * 24) + 12)console.log(((16 * 24) + 12).toString()) 都返回 396。只是后者以字符串格式返回。计算完全一样。在这里使用.toString() 绝对没有意义。和不。 +总是附加。处理数字时,它会添加。就像它在几乎所有其他编程语言中所做的一样。
        猜你喜欢
        • 1970-01-01
        • 2017-07-15
        • 2017-01-14
        • 2014-11-15
        • 1970-01-01
        • 2013-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多