簡體   English   中英

為什么我的Javascript全局變量僅更新一次? jQuery的最后一個選擇器錯誤?

[英]Why do my Javascript global variables only update once? jQuery last-child selector error?

我正在嘗試學習jQuery並在JS Fiddle上測試想法,而我似乎腦子僵硬了。

下面的代碼應顯示表的一行,該表的末尾帶有“ +”以添加新行。 第一次單擊時,它將為新行正確分配新ID(並將新行中的值重置為原始狀態,將舊行的“ +”更改為“-”)。 我不明白為什么在第一次運行代碼后,oldID和newID的值不會繼續增加。

它讀取“ 32”作為舊的最后一個子代的數字部分,然后創建一個新行,並在表中附加“ 33”,但是在使用最后一個子選擇器重新計算id之后,似乎並沒有實際選擇NEW最后一個孩子。

雖然歡迎提出有關如何使代碼更好的建議,但我確實想特別了解我當前代碼中缺少的內容,盡管可能不太好。

謝謝!

<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;
});

我認為您的問題是,您永遠不會約束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
});

這樣,每次添加新人員時,您都不必綁定新的處理程序,該處理程序已經可以使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM