2013-08-07 74 views
0

我有一个问题。现在jQuery跨度到输入,反之亦然

$(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/ 所以,任何想法如何做,将不胜感激。

预先感谢您。

+0

你所说的“第一时间”是什么意思?如果我点击和关闭文本,它可以正常工作。 – DevlshOne

+0

工作正常。有什么问题...? –

+0

他意味着与第二个代码,而不是.live代码,你可以看到这里http://jsfiddle.net/hW3vk/4/ – Anton

回答

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(); 
    }); 
}); 

您需要更改,以便在on参数,为它工作作为活做的$(document)

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

相反,你可以使用父母选择这样就缩小了旅游

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

+0

就是这样!谢谢 !我会在5分钟内接受这个答案:) –

1

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

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

我不知道这个问题的答案&早contentediable,但如果它,或可能是有益的,所有主流浏览器都支持它,所以我需要整个解决方案是这样的:

<span contenteditable="true">Click aici</span>