2014-09-30 144 views
0

函數不會附加到新創建的輸入框中。 請檢查我的代碼此鏈接動態DOM創建問題

[請檢查驗證碼] [1]

$("#datepicker").datepicker(); 
 

 

 
$("button").click(function(){ 
 
    
 
    $(".add").html('<input id="datepicker" placeholder="click here to open calendar " type="text" />'); 
 
    
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class='add'><input id="datepicker" placeholder="click here to open calendar " type="text" /></div> 
 
<button>Add input again </button>

depen.io/anon/pen/adLzi

+2

請包括相關的([MCVE(http://stackoverflow.com/help/mcve))代碼在這裏,在你的問題。不要期望人們通過互聯網上的鏈接來獲得幫助。 – 2014-09-30 10:06:31

回答

0
$("button").click(function(){ 

    $(".add").html('<input id="datepicker" placeholder="click here to open calendar " type="text" />'); 

    // move to here your cod 
    $("#datepicker").datepicker(); 

}); 

上$(「。add」)。html(...)表示刪除並創建新的DOM對象

然後失去意義$(「#datepicker」)。datepicker();

+0

我必須替換content.Not append。 – Vis 2014-09-30 10:05:01

+0

多數民衆贊成好..但爲什麼這個功能沒有得到與我們添加使用JavaScript的InputBox附加? – Vis 2014-09-30 10:11:53

+0

你想要什麼?使用datepicker? – easywaru 2014-09-30 10:14:09

0

試試這個

$("button").click(function(){ 
    $("#datepicker").val(""); 
    $("#datepicker").focus(); 
}); 

Demo

1

當你點擊按鈕,這是正在執行的代碼:

$("button").click(function(){ 
    $(".add").html('<input id="datepicker" placeholder="click here to open calendar " type="text" />'); 
}); 

這裏做的事情是用新的替換日期選擇器。除了附加事件重新附加問題外沒有任何問題。

TL:DR,使用此代碼:

$("button").click(function(){ 
    var el = $('#datepicker'); 
    $.datepicker._clearDate(el); 
}); 

編輯

即使我不知道確切的原因,爲什麼會這樣,但是這可能是因爲內部,jQuery UI的沒有鏈接以前的DOM元素,它是懸掛的。這也會導致內存泄漏。

0

嘗試插件初始化移動到您的document.ready功能:

$(document).ready(function() { 
$("#datepicker").datepicker();` 
}); 

$("button").click(function(){ 
 
    
 
    $(".add").html('<input id="datepicker" placeholder="click here to open calendar " type="text" />'); 
 
    
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class='add'><input id="datepicker" placeholder="click here to open calendar " type="text" /></div> 
 
<button>Add input again </button>