[英]jQuery replace DIV to INPUT and vice versa
我正在實現一種內聯編輯功能。
因此,最初將顯示日期標簽(例如 05/01/1999),單擊它時,它將被替換為具有相同值(05/01/1999)的輸入框。 現在用戶可以使用 jQuery UI 日期選擇器選擇任何日期,並在選擇任何日期(比如 05/01/2005)時,我會再次顯示一個標簽(05/01/2005)
目前我正在使用以下代碼;
$(document).on("click",".editableDateTxt", function () {
var currElmModelAttr = $(this).attr('data-model-attr');
var input = $('<input />', {'type': 'text','name':currElmModelAttr, 'style':'width:100px','class':'datePicker', 'value': $(this).html()});
var parent = $(this).parent();
parent.append(input);
$(this).remove();
input.datepicker().focus();
});
實現相同的最佳方法是什么?
現在是關鍵點:我正在使用jQuery UI datepicker ,它在內部使用 jQuery data()。 所以我不想在從 div > input 跳轉時松開它,反之亦然。
如何修改上面的代碼以考慮保留 jQuery data() 信息?
var MyView = BaseModalView.extend({
el: "#myModalContainer",
initialize: function() {
var self = this;
},
render: function() {
var self = this,
$el = $(self.el);
$el.find(".datePicker").datepicker();
self.initEventListeners();
},
initEventListeners: function() {
var self = this,
$el = $(self.el);
var $this;
$(document).on("click", ".editableDateTxt", function () {
var currElmModelId = $(this).attr('data-model-id');
var currElmModelAttr = $(this).attr('data-model-attr');
$this = $(this);
var input = $('<input />', {
'type': 'text',
'name': currElmModelAttr,
'data-model-id': currElmModelId,
'data-model-attr': currElmModelAttr,
'style': 'width:100px',
'class': 'datePicker',
'value': $(this).text()
});
$(this).replaceWith(input);
input.datepicker({
onSelect: function (date) {
$this.text(date);
input.replaceWith($this);
// input.blur();
}
}).focus();
$(document).on("blur change", "input", function () {
setTimeout(function () {
var value = input.val();
$this.text(value);
input.replaceWith($this);
}, 100);
});
});
}
你可以用replaceWith()
更好地交換
$(document).on("click", ".editableDateTxt", function () {
var currElmModelAttr = $(this).attr('data-model-attr');
var $this = $(this);
var input = $('<input />', {
'type': 'text',
'name': currElmModelAttr,
'style': 'width:100px',
'class': 'datePicker',
'value': $(this).text()
});
$(this).replaceWith(input);
input.datepicker({
onSelect: function (date) {
$this.text(date);
input.replaceWith($this);
console.log(date);
}
})
});
另外,我建議您隱藏/顯示元素,在這種情況下會更好,而不是每次都創建和交換元素。
這是一個更簡單的版本,正如@Shaunak D 所建議的,使用基本的hide()
和show()
。
^_^ jsfiddle 示例
html代碼:
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<div id="lbl"></div>
<input type='text' id="date-picker" />
JS代碼:
$('#lbl').html('2014-01-01');
$('#date-picker').hide();
$('#date-picker').datepicker({
onSelect: function(date) {
$('#lbl').html(date);
$(this).hide();
$('#lbl').show();
}
});
$('#lbl').click(function(){
//alert();
$(this).hide();
$('#date-picker').show();
});
最好的方法是使用帶有日期選擇器的只讀輸入字段。 使用 div 並替換為輸入字段是否有任何原因?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.