2017-08-25 21 views
0

我想用JQuery啓動一個Ajax動作。爲此,我有以下的代碼,這也可以工作:在'Enter'上提交一個文本框或者如果jQuery發生變化

jQuery的

$(document).on('blur', '.priceConference', function(){ 

         var id = $(this).data("id2"); 
         var priceConference = $(this).text(); 
         edit_data(id,priceConference, "priceConference"); 

      }); 

HTML:

<td class="priceConference" data-id2="'.$row["idBookingConference"].'" contenteditable>'.$row["priceConference"].' €</td> 

不過,我不希望啓動edit_data()功能,當沒有焦點在領域('模糊')。但是,如果內容真的發生了變化,或者用戶輸入密鑰「Enter」,我想開始執行命令。

我用以下代碼測試過它,但它不起作用。它會是什麼?

新的jQuery代碼

$(document).ready(function(){ 
       $(".priceConference").change(function(){ 
        var id = $(this).data("id2"); 
        var priceConference = $(this).text(); 
        edit_data(id,priceConference, "priceConference"); 
       }); 
      }); 

非常感謝您的幫助。

+0

應該'CONTENTEDITABLE>'不'CONTENTEDITABLE ='與'='? –

+0

contenteditable屬性指定元素的內容是否可編輯。但是,如果你寫contenteditable =「true」或者只寫),這並不重要。他們兩人都很好。 :) –

+0

[contenteditable MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable)該屬性是一個枚舉值,而不是布爾值。這意味着明確使用true,false或空字符串中的一個是強制性的,並且不允許使用像

回答

0

對於contenteditable元件進入,使用​​事件。 change事件不做任何事情。爲了只在值發生變化時調用函數,我已經將原始值添加到發送Ajax之前檢查的元素的數據中。

$('td').on('keydown', function(e) { // For capturing the Enter key 
 
    if (e.keyCode === 13 && $(this).text() !== $(this).data('originalValue')) { 
 
    $(this).data('originalValue', $(this).text()); 
 
    e.preventDefault(); // no newline 
 
    console.log('Call Ajax'); 
 
    } 
 
}).on('focusin', function(e) { // Set value on click 
 
    $(this).data('originalValue', $(this).text()); 
 
}).on('focusout', function(e) { // Check if value changed on click away 
 
    if ($(this).text() !== $(this).data('originalValue')) 
 
    console.log('Call Ajax'); 
 
});
td { 
 
    width: 100px; 
 
    border: 1px solid black; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tbody> 
 
    <tr> 
 
     <td contenteditable="true"></td> 
 
    </tr> 
 
    </tbody> 
 
</table>

+0

哦,非常感謝你:) –

0

喲可以處理下面的代碼

<td onKeyPress='return submitEnter(event)' ></td> 

     function submitEnter(e) { 
       if((e && e.keyCode == 13) || e == 0) { 
       // enter handled here 
       } 
      } 
+0

不幸的是,它不工作。系統創建一個換行符,而不是一個單擊事件。 –

相關問題