2013-08-07 75 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>