使用jQuery进行编辑

时间:2015-03-06 14:43:51

标签: jquery

参考this fiddle,我正在实施一个非常基本的编辑系统。

这是剧本:

// fire all the click on the spans having the class "edit"
$(document).on('click', '.edit', function() {
    // toggle the spans and show the one to edit the data
    $(this).closest('td').find('span').toggle();
    // listen for the first click outside of the span with class "editing" that is ":visible"
    $(document).one('click', ':not(.editing:visible)', function() {
        // toggle the span with class "editing" that is ":visible"
        $('.editing:visible').closest('td').find('span').toggle();
    });
});

如果关闭.editing点击table之外的td,可以正常工作,但如果您点击另一个.editing.editing已打开,则会正确关闭之前的table,但在{{1}}之外单击之前,它不会让您打开新的{{1}}!代码有什么问题?

1 个答案:

答案 0 :(得分:1)

执行此操作相当复杂,但假设您要编辑某些文本,则需要一些基于输入的元素。因此,您只需将blur事件处理程序绑定到此输入并关闭它们。

完整示例是here,jquery代码:

$(document).on('click', '.edit', function(event) {
    $(this).closest('td').find('span').toggle().find('input').focus();
});

$(document).on('blur', 'input.editing', function(event) {
    $(this).closest('td').find('span').toggle();
});

评论后编辑:

$(document).on('click', 'body', function(event) {
    var target = $(event.target);
    $('.editing').not(target).hide().sibling('.edit').show();
});

这应该对你有所帮助。基本上每次点击它都会隐藏未点击的所有.editing元素。

第二次编辑:

fiddle,以及一些代码 -

$(document).on('click', '.edit', function(event) {
    $(this).closest('td').find('span').toggle().find('select').focus();
});

$(document).on('blur', 'select._target', function(event) {
    $(this).closest('td').find('span').toggle();
});

$(document).on('change', 'select._target', function(event){
    $(this).trigger('blur');
});

基本上,我会自动将选择内容集中在跨度内,并允许模糊完成所有工作。更改事件用于选择某个值 - 假设您希望在选择后关闭选择。小提琴测试,希望它会有所帮助:)

对于选择和输入版本更改前两个事件处理程序,如下所示:

$(document).on('click', '.edit', function(event) {
    $(this).closest('td').find('span').toggle().find('select, input').focus();
});

$(document).on('blur', 'select._target, input._target', function(event) {
    $(this).closest('td').find('span').toggle();
});