2014-01-29 100 views
-2

我有一個文本跨度,我想用jQuery聽,如果訪問者點擊文本,它應該用輸入字段(這是從開始隱藏)替換該文本。如果訪問者將輸入字段留空並將其置於焦點之外,則應該隱藏輸入並再次顯示文本。Jquery切換文本到輸入字段點擊時

幫助將不勝感激。

編輯:

這是當前的代碼,我有:

$("span").click(function() { 
$(this).hide(); 
$("input").toggle(); 
}); 
+0

爲了得到這個答案的網站,你必須嘗試在自己的東西,然後問一個具體問題,你卡住了。 –

+0

謝謝,我編輯了我的帖子。 – rac

+0

@rac這個網站上有很多問題已經有答案。 –

回答

0

如果您在DOM中移動東西,則無需創建隱藏元素。您可以使用jQuery的.replaceWith()以較少的代碼執行此操作。

$('body').on('click', '#mySpan', function (event) { 
    $(this).replaceWith("<input id='myInput' type='text' />"); 
    $('#myInput').focus(); 
}); 

$('body').on('focusout', 'input', function (event) { 
    if($(this).val() == ""){ 
    $(this).replaceWith("<span id='mySpan'>Sample Text</span>"); 
    } 
}); 

小提琴 - http://jsfiddle.net/jX7rM/2/

+0

謝謝你這個作品太棒了! – rac

0

試試這個:

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

Fiddle

0

試試這個代碼:

DEMO

$("span").click(function(){ 
    $("input").show().change(function(){ 
     $("span").show(); 
     $(this).hide(); 
    }); 
    $(this).hide(); 

    }); 
0

您是否在尋找contenteditable跨度?

設置你的跨度contenteditable="true"

檢查小提琴。 JSFiddle