2013-10-07 32 views
3

我有一個非標準的HTML標籤有值:如何更改/編輯jquery/javascript的標籤值?

<label id="telefon" value="101"></label> 

我喜歡通過點擊標籤來編​​輯這個值並在出現新的文本框的值(如value="202")進入。

我該怎麼做這麼棘手的事情?

我嘗試過使用jQuery的功能,但它真的不慣於工作:

$(function() { 

    $('a.edit').on("click", function(e) { 
    e.preventDefault(); 
    var dad = $(this).parent().parent(); 
    var lbl = dad.find('label'); 
    lbl.hide(); 
    dad.find('input[type="text"]').val(lbl.text()).show().focus(); 
    }); 

    $('input[type=text]').focusout(function() { 
    var dad = $(this).parent(); 
    $(this).hide(); 
    dad.find('label').text(this.value).show(); 
    }); 

}); 
+3

您能否提供完整的HTML標記,例如'edit'錨點,'input'類型文本等? –

+0

嘿,它會很簡單,你可以請你在jsfiddle發佈你的代碼, –

+0

你應該使用innerHTML而不是像'''然後你可以用'.html'改變標籤innerHTML或'.text' – ncm

回答

9

http://jsfiddle.net/jasuC/,因爲你沒有提供的標記,看看這個工作示例

$(document).on("click", "label.mytxt", function() { 
    var txt = $(".mytxt").text(); 
    $(".mytxt").replaceWith("<input class='mytxt'/>"); 
    $(".mytxt").val(txt); 
}); 

$(document).on("blur", "input.mytxt", function() { 
    var txt = $(this).val(); 
    $(this).replaceWith("<label class='mytxt'></label>"); 
    $(".mytxt").text(txt); 
}); 
+0

這項工作甚至更好,如果我們在'input'類型中設置'id',比如「 –

1

你不需要jquery。

爲了使幾乎所有標籤元素可編輯,將contentEditable設置爲true

因此,您可以使用HTML的默認功能進行更改。

0

//你可以添加一個事件監聽到你的表單標籤和代碼的處理程序,這將是共同的所有標籤(Fiddle HERE

// HTML

<form id="myform"> 
    <label style="background-color:#eee" title="101">Value is 101<label> 
</form> 

// JS

$(function(){ 
    $('#myform').on('click',function(e){ 
     var $label = $(e.target), $form = $(this), $editorInput = $('#editorInput'), offset = $label.offset(); 
     if($label.is('label')){ 
      if(!$editorInput.length){ 
       $editorInput = $('<input id="editorInput" type="text" value="" style="" />').insertAfter($label); 
      } 
      $editorInput.css('display','inline-block') 
       .data('editingLabel', $label.get(0)) 
       .focus() 
       .keydown(function(e){ 
        var $l = $($(this).data('editingLabel')), $t = $(this); 
        if(e.which == 13){ 
         $l .attr('title', $t.val().replace(/(^\s+)|(\s+$)/g,'')) 
          .text('value is now ' + $l.attr('title')); 

         // UPDATE YOUR DATABASE HERE 

         $t.off('keydown').css('display','none'); 
         return false; 
        } 
       }); 
     } 
    }); 
}); 

// CSS的位

#editorInput{display:none;padding:2px;border:1px solid #eee;margin-left:5px}