jQuery跨度输入,反之亦然

Leo*_*atu 0 html jquery input live

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

   $(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();
    });
    });
Run Code Online (Sandbox Code Playgroud)

和HTML现在:

<span>Click aici</span>
Run Code Online (Sandbox Code Playgroud)

所以,这显然适用于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();
    });
    });
Run Code Online (Sandbox Code Playgroud)

要不就:

$(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();
    });
    });
Run Code Online (Sandbox Code Playgroud)

但这只是第一次工作.

请看这里的演示:http://jsfiddle.net/hW3vk/ 所以,任何想法如何做到这一点将不胜感激.

先感谢您.

Spo*_*key 7

$(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();
    });
});
Run Code Online (Sandbox Code Playgroud)

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

$('(parent) static selector').on('event', 'dynamic selector', function(){...})
Run Code Online (Sandbox Code Playgroud)

而不是$(document)你可以使用父选择器,因此它将缩小旅行范围

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