1

我有个问题。看看下面的代码:

   $(function () {
    $('span').live('click', function () {
        var input = $('<input />', {
            'type': 'text',
                'name': 'aname',
                'value': $(this).html()
        });
        $(this).parent().append(input);
        $(this).remove();
        input.focus();
    });

    $('input').live('blur', function () {
        $(this).parent().append($('<span />').html($(this).val()));
        $(this).remove();
    });
    });

现在和html:

<span>Click aici</span>

所以,这显然是有效的,直到 jquery 1.8.3,包括在内。在 1.8.3 .live() 被弃用之后,我们需要使用 .on()。所以代码变成了:

$(function () {
    $('span').on('click', function () {
        var input = $('<input />', {
            'type': 'text',
                'name': 'aname',
                'value': $(this).html()
        });
        $(this).parent().append(input);
        $(this).remove();
        input.focus();
    });

    $('input').on('blur', function () {
        $(this).parent().append($('<span />').html($(this).val()));
        $(this).remove();
    });
    });

要不就:

$(function () {
    $('span').click(function () {
        var input = $('<input />', {
            'type': 'text',
                'name': 'aname',
                'value': $(this).html()
        });
        $(this).parent().append(input);
        $(this).remove();
        input.focus();
    });

    $('input').blur(function () {
        $(this).parent().append($('<span />').html($(this).val()));
        $(this).remove();
    });
    });

但这只是第一次。

请参阅此处的演示:http: //jsfiddle.net/hW3vk/ 因此,任何想法如何做到这一点将不胜感激。

先感谢您。

4

2 回答 2

9
$(function () {
    $(document).on('click', 'span', function () {
        var input = $('<input />', {
            'type': 'text',
                'name': 'unique',
                'value': $(this).html()
        });
        $(this).parent().append(input);
        $(this).remove();
        input.focus();
    });

    $(document).on('blur', 'input', function () {
        $(this).parent().append($('<span />').html($(this).val()));
        $(this).remove();
    });
});

您需要更改on参数才能使其像现场一样工作

$('(parent) static selector').on('event', 'dynamic selector', function(){...})

而不是$(document)您可以使用父选择器,这样它会缩小旅行范围

这里还有一个小提琴http://jsfiddle.net/Spokey/hW3vk/5/

于 2013-08-07T13:04:19.830 回答
2

我搜索了这个并找到了我想要的答案。

然后我发现了“contenteditable”属性,它取代了我想使用 jQuery 将跨度更改为输入的原因......

我不知道这个问题和答案是否早于 contentediable,但如果它确实或可能有帮助,所有主要浏览器现在都支持它,所以我需要的整个解决方案是这样的:

<span contenteditable="true">Click aici</span>
于 2015-05-21T05:58:42.963 回答