[英]$(this) not working on dynamically created elements
我將輸入字段附加到動作的div上。 當我嘗試使用$(this).val()
訪問輸入字段中的值時,我只是得到空值。
$('#div').append('<td class = "fund-amount"><input type="number" class="custom-amount" id='+value.response_code+' placeholder="Rs."></td>');
根據操作,可以在div上附加任意數量的輸入字段。 我想獲取在每個字段上輸入的值。 當我嘗試使用下面的這種方法來獲取價值時,它沒有奏效。 但是當我得到動態創建的id值並代替$(this)
它起作用了
$(document).keyup('.custom-amount',function(){
console.log($(this).val()); //just logging empty
console.log($(this).attr('id')); //Logged undefined
})
但是這個有效
$(document).keyup('#100520',function(){
console.log($('#100520').val());//works
console.log($('#100520').val());//works
});
我的方法有什么問題嗎?
$(document).on('key-up','.custom-amount',function(){
console.log($(this).val()); //just logging empty
console.log($(this).attr('id')); //Logged undefined
})
你有嘗試過嗎?
$(document).on('keyup', '.custom-amount', function(){
console.log($(this).val());
console.log($(this).attr('id'))
});
試試下面的代碼
$('#div').append('<td class = "fund-amount"><input type="number" class="custom-amount" id='+100520+' placeholder="Rs."></td>'); $('.custom-amount').keyup(function() { console.log($(this).val()); // value console.log($(this).attr('id')); // id })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id= "div"> </div>
在處理程序中調用$(this)
可以正常工作。 因為您正在處理類似$(document).keyup
這樣的事件, $(document).keyup
您的處理程序是在document
元素而不是元素本身上調用的,因此this
是引用document
。
但是,當您向處理函數提供事件arg對象時,可以使用其屬性target
,該target
將引用觸發事件的元素,如下所示:
$(function() { $(document).on("keyup", ".custom-amount",function(e){ console.log($(e.target).val()); console.log($(e.target).attr('id')); }) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="custom-amount" id="some-id" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.