[英]how to change/edit value of label with jquery/javascript?
我有一個標准的HTML標簽值:
<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();
});
});
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);
});
你不需要jquery。
要使幾乎所有標記元素都可編輯,請將contentEditable
設置為true
。
因此,您可以使用HTML的默認功能進行更改。
//您可以向表單標記添加一個事件監聽器,並對所有標簽共有的處理程序進行編碼( 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}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.