[英]Getting and Setting Values for Dynamically Created HTML inputs using Javascript
我在 Javascript 中動態創建了“輸入”元素,並將“插入后”附加到已經創建的“div”中。 這些“輸入”出現了,但我無法逐步獲取或更改它們的值,我以后需要使用這些值。
為目錄中的每個文件添加“輸入”元素,並制作“id”以便使用加號和減號按鈕獲取和更改輸入的值,但是當我嘗試獲取值時出現此錯誤。
Uncaught TypeError: Cannot read property 'value' of null
使用的基本代碼片段如下所示:
Javascript:
$.ajax({
url: "http://localhost:8888/file",
success: function(data){
var filename = this.href.replace(window.location.host, "").replace("http://", "").replace("/","").replace(".csv", "");$(data).find("a:contains(" + fileextension + ")").each(function () {
if(counter == 0){
$('<div class="col-md-3 ' + counter + '"></div>').appendTo('#stock_types');
$('<a href = "#" onclick="return false; onclick=removing();" class = "is_stock"> </a>').html(filename).appendTo('.'+ counter).attr('id', filename);
$('<button type="button" onclick="adding()" class = "btn btn-default plus_"> + </button>').insertAfter($( "#" + filename )).attr('id','plus_'+filename);
$('<input class = "stock_amount" name="input_' + filename + '" id = input_'+ filename +' value = "0" ">').insertAfter($( "#plus_" + filename ));
$('<button type="button" onclick="subtracting()" class = "btn btn-default minus_"> - </button>').insertAfter($( '#input_' + filename)).attr('id','minus_'+filename);
function adding(){
raw_id = '';
raw_id = raw_id + $(this).attr('id');
var new_id = raw_id.replace("plus", "input");
console.log(new_id);
current_val = document.getElementById(new_id).value;
current_val = current_val + 1;
console.log(current_val);
};
我的最終目標是獲取並增加動態創建的輸入的值。 提前致謝。
$(this).attr('id')
這將不起作用,因為該函數尚未附加到任何對象(因此this
將返回undefined
)。 您可以將所需元素作為參數傳遞給函數。 你可以這樣做:
$('<button type="button" onclick="adding(document.querySelector('.stock_amount')[0])" class = "btn btn-default plus_"> + </button>').insertAfter($( "#" + filename )).attr('id','plus_'+filename);
並在添加功能中:
function adding(input){
raw_id = '';
raw_id = raw_id + $(input).attr('id');
...
}
jQuery 支持開箱即用的動態元素。 不需要帶有onclick
屬性的 vanilla js 等等...
var btn = $('<button>', {
text: ' + ',
'class':'btn btn-default plus'
});
function adding(event){
// adding...
}
btn.on('click', adding).insertAfter($('.....whatever'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.