我想用JQuery启动一个Ajax操作。为此,我有以下代码,它也可以工作:
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");
});
});
非常感谢您的帮助。
对于contenteditable
元素,请使用keydown
事件。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>
Yo 可以使用以下代码处理 enter
<td onKeyPress='return submitEnter(event)' ></td>
function submitEnter(e) {
if((e && e.keyCode == 13) || e == 0) {
// enter handled here
}
}