我是JavaScript的新手(非常新的编程,目前正在学习Django,JQuery和JavaScript)。无论如何,我正在尝试编写一个JS函数,允许用户单击DOM中创建输入字段的元素,以便用户可以动态更改元素的文本内容。然后,我将发送一个JSON / AJAX请求来更改数据库的内容以反映更改。
我已经开始工作,但注意到一个小问题。我将3个事件绑定到函数; keyup,focusout和keydown。当用户点击远离输入时以及按下回车键时,我正在尝试捕获按下时的每个键(以动态更新DOM中的另一个元素以反映键入的更改)。点击并触发每个按键按下即可获得一种享受,但是按下返回会给我带来麻烦。我不得不添加keydown事件来捕获它。然而,似乎正在发生的是所有三个事件都在触发(即我的AJAX POST被发送三次)。无法绕过这个问题。尝试了一些事情(即禁用事件冒泡),但是我对JS很新,所以有点超出我的深度并解决了这个问题。预先感谢发布的任何答案。下面是我写的JS,可能没有最高效的,我确信我会及时学会如何简化它。
如果按下回车键,我怎样才能确保运行一次功能?
提前致谢,代码如下。
/* track key pesses on menu name being updated */
$(document).on('keydown keyup focusout','.name_input',function(event){
/* added to try and fix multiple AJAX requests, doesnt seem to work though */
event.cancelBubble = true;
var levelurl;
var menu_id = parseInt($(this).attr("menu_id"));
var menu_root = $(this).attr("menu_root");
var el = '#subrelative' + menu_id;
var $input = $(this);
if (menu_root.length == 1){
levelurl = '/pages/ajax_request/menu/';
}
else{
levelurl = '/pages/ajax_request/submenu/';
}
/* strip unwanted characters from the input */
$input.val($input.val().replace(/[^A-Za-z-_?&\d]/g, '' ));
if (event.type == 'focusout' || event.which === 13){
event.preventDefault();
$.ajax({
url: levelurl,
type: 'POST',
data: {id: menu_id, action: "modify_name"},
dataType: 'json',
success: function(data){
if (data.status){
/* add stuff once backend AJAX stuff is finished */
}
else{
$('#infomodalTitle').html(data.title);
$('#infomodalBody').html(data.message);
$('#infomodalFooter').html('<a href="javascript:location.reload(true)"><button type="button" class="btn btn-success btn-xs">Reload Page</button></a>');
$('#infomodal').modal('show');
};
/* apparently should stop event bubbling but doesnt. Probably not understanding the event bubbling issue properly */
return false;
},
failure: function(data){
/* display info modal error message */
infotitle = "<font color='red'><b>Error</b></font>"
$('#infomodalTitle').html(infotitle);
$('#infomodalBody').html('<p>Server processing error</p>');
$('#infomodalFooter').html('<button type="button" class="btn btn-success btn-xs" data-dismiss="modal">Dismiss</button>');
$('#infomodal').modal('show');
}
});
}
else{
var eltext = menu_root + $input.val() + '/';
$(el).html(eltext);
};
});
/* ******************** */
答案 0 :(得分:0)
更改此代码:
var eventFired = false;
$(document).on('keyup focusout','.name_input',function(event){
if( !eventFired ) {
eventFired = true;
//Your code
eventFired = false;
}
});