【问题标题】:Why do my Javascript global variables only update once? jQuery last-child selector error?为什么我的 Javascript 全局变量只更新一次? jQuery最后一个子选择器错误?
【发布时间】:2013-08-16 16:12:01
【问题描述】:

我正在尝试学习 jQuery 并在 JS Fiddle 上测试一些想法,但我似乎大脑一片空白。

下面的代码应显示表格的一行,该行末尾带有“+”以添加新行。第一次单击时,它会将新 ID 正确分配给新行(并将值重置为新行中的原始状态,将旧行的“+”更改为“-”)。我不明白为什么 oldID 和 newID 的值在第一次运行代码后不会继续增加。

它将“32”读取为旧的最后一个孩子的数字部分,然后创建一个新行,并将“33”附加到表中,但之后使用最后一个孩子选择器重新计算 id 似乎实际上并没有选择新的最后一个孩子。

虽然欢迎提出有关如何使代码更好的建议,但我真的很想知道我在当前代码中缺少什么,尽管它可能不优雅。

谢谢!

<table>

<tbody id="investigators">
<tr id="investigator.32">

  <td>
    <input name="person.32" id="person.32"
           type="text" value=""
           placeholder="Lastname, Firstname" 
           onfocus="this.select();" />
  </td>

  <td style="text-align:center" id="add_more.32">
    <img src="add_green.svg"
         alt="[+]" title="Add investigator"
         style="height:1em; width:1em;" />
  </td>

</tr>
</tbody>

以及 Javascript/jQuery 代码:

var oldID = parseInt($("#investigators :last-child")
                       .attr("id").split(".")[1]);
var newID = oldID+1;
$("#add_more\\."+oldID).click(function(){
  var $newPI = $("#investigator\\."+oldID).clone(true);
  $newPI.find("#person\\."+oldID)
    .val(null)
    .attr("placeholder","Jungle, George of")
    .attr("name","person."+newID)
    .attr("id",  "person."+newID);
  $newPI.find("#add_more\\."+oldID)
    .attr("id","add_more."+newID);
  $newPI
    .attr("id","investigator."+newID);
  $newPI.appendTo("#investigators");
  $("#add_more\\."+oldID+" :first-child")
    .attr("src","delete_red.svg")
    .attr("alt","[X]")
    .attr("title","Remove investigator");
  oldID = parseInt($("#investigators :last-child")
                       .attr("id").split(".")[1]);
  newID = oldID+1;
});

【问题讨论】:

  • 你能链接你的jsfiddle吗?

标签: javascript jquery jquery-selectors global-variables


【解决方案1】:

我认为你的问题是你永远不会绑定到新创建的人的click。调用 $("#add_more\\."+oldID).click(...) 将绑定到原始项目,但不会绑定到新项目,因为 oldID 发生了变化。

相反,我认为您应该将类​​添加到您的元素中:

<td>
<input name="person.32" id="person.32"
       class="person" <!-- the important line -->
       type="text" value=""
       placeholder="Lastname, Firstname" 
       onfocus="this.select();" />
</td>

然后,你可以使用类似jQuery.on:

$(document).on("click", "person", function() {
    // Check that this is the last person here
});

这样,每次添加新人时,您都不必绑定新的处理程序,它已经可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-13
    • 2019-04-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    相关资源
    最近更新 更多