我正在学习本教程:
http://www.9lessons.info/2011/03/live-table-edit-with-jquery-and-ajax.html
我的补充最多的内容是ajax / json / dynamic。我添加了一个动态填充的选择框。当我尝试在选择下拉列表中选择某些内容时,它会自动关闭。我假设由于这个原因:
$(".editbox").mouseup(function(){
return false
});
我试图对此使用一些变体:
$('input[type=select]').click(function(event){event.stopPropagation()});
但是我的兔子洞比我目前的理解所允许的还要深。 任何建议都将不胜感激。
答案 0 :(得分:1)
您可以通过使用if语句将代码包装在tr的click事件中来解决此问题,该语句检查实际单击了哪个元素。这会导致您的代码仅在用户直接点击具有相应类别的<td>
或<span>
时隐藏/显示输入。这将允许您摆脱'.editbox'mouseup事件处理程序。
jsFiddle(小提琴中的第一行显示一个选择框而不是两个输入,因此您可以看到此代码有效。在小提琴中也会注释ajax调用。)
$(document).ready(function() {
$(".edit_tr").click(function(e) {
if ($(e.target).hasClass('edit_td') || $(e.target).hasClass('text')) {
var ID = $(this).attr('id');
$("#first_" + ID).hide();
$("#last_" + ID).hide();
$("#first_input_" + ID).show();
$("#last_input_" + ID).show();
}
}).change(function() {
var ID = $(this).attr('id');
var first = $("#first_input_" + ID).val();
var last = $("#last_input_" + ID).val();
var dataString = 'id=' + ID + '&firstname=' + first + '&lastname=' + last;
$("#first_" + ID).html('<img src="load.gif" />'); // Loading image
if (first.length > 0 && last.length > 0) {
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html) {
$("#first_" + ID).html(first);
$("#last_" + ID).html(last);
}
});
}
else {
alert('Enter something.');
}
});
// Outside click action
$(document).mouseup(function(e) {
if (!$(e.target).hasClass('editbox')) {
$(".editbox").hide();
$(".text").show();
}
});
});
上面的相关代码是:
$(".edit_tr").click(function(e) {
if ($(e.target).hasClass('edit_td') || $(e.target).hasClass('text')) {
var ID = $(this).attr('id');
$("#first_" + ID).hide();
$("#last_" + ID).hide();
$("#first_input_" + ID).show();
$("#last_input_" + ID).show();
}
})
不要忘记删除此代码:
$(".editbox").mouseup(function() {
return false
});
编辑:您需要在“文档”点击处理程序中执行类似的操作。除此之外,如果目标具有“editbox”类,则忽略了点击次数。
// Outside click action
$(document).mouseup(function(e) {
if (!$(e.target).hasClass('editbox')) {
$(".editbox").hide();
$(".text").show();
}
});