2012-11-05 92 views
0

我的PHP代碼有這樣的HTML代碼生成更改事件觸發多次

<tr class="edit_tr"> 
<td>a1</td> 
<td class="edit_td"> 
<span id=" " class="text"></span> 
<input id="144" class="25" type="text" value=""> 
</td> 
<td class="edit_td"> 
<span id=" " class="text"></span> 
<input id="144" class="26" type="text" value=""> 
</td> 
<td class="edit_td"> 
<span id=" " class="text"></span> 
<input id="144" class="27" type="text" value=""> 
</td> 
</tr> 

這是JavaScript,我使用:

$(document).ready(function(e) { 
    $(".edit_tr").click(function(){ 
     var id = $(this).attr("id"); 
     // we have here tow states :#1 and #2 
     //#1 there is no Id, and thats mean we want to insert to database 
     if(typeof id == 'undefined'){ 
      $(this).children("td").children("input").change(function(){ 
       var stateId = $(this).attr("class"); 
       var alternativeId = $(this).attr("id"); 
       alert("state is :"+ stateId); 
       alert("alternativeId is :"+ alternativeId); 
       //return false;   
      }); 

     } 
     //#2 there is an id, so we want to update the value 
     else{ 
      alert("there is id "); 

     } 
    }); 
}); 

的問題,當我在第一次改變輸入的值時間它工作正常,但當我嘗試改變價值另一次,改變事件激發多次

請任何幫助,我明白它

+0

沒有嚴格與你的問題有關,但使用'console.log'用於調試目的而不是'alert' - 它可以爲您節省很多點擊。 – moonwave99

+0

注意:您正在使用class/id錯誤。也許像這樣存儲它:'data-state =「26」data-alternativeId =「144」' –

+0

該行的點擊有點奇怪。你喜歡按鈕嗎?何時會發生保存操作? –

回答

3

試試這個代碼

$(document).ready(function(e) { 

    $(".edit_tr").click(function(){ 
     var id = $(this).attr("id"); 
     // we have here tow states :#1 and #2 
     //#1 there is no Id, and thats mean we want to insert to database 
     if(typeof id != 'undefined'){ 
      alert("there is id "); 

     } 
    }); 



    $(".edit_tr").find("input").change(function(){ 
     var stateId = $(this).attr("class"); 
     var alternativeId = $(this).attr("id"); 
     alert("state is :"+ stateId); 
     alert("alternativeId is :"+ alternativeId); 
     //return false;   
    }); 

}); 
+0

它可行,但問題在哪裏? – Kamal

+2

每當您點擊tr時,您都會一次又一次地綁定更改事件。正如我向你展示的那樣,綁定更改事件一次。 –

3

每當你點擊$(「 edit_tr」),又添加了另一個事件處理程序,所以這就是爲什麼代碼觸發多次

+0

我要做什麼?糾正這個問題 – Kamal