[英]$(this) not working on dynamically created elements
I am appending input fields to a div on a action. 我将输入字段附加到动作的div上。 When i try to access the value inside the input field using
$(this).val()
i am just getting empty values. 当我尝试使用
$(this).val()
访问输入字段中的值时,我只是得到空值。
$('#div').append('<td class = "fund-amount"><input type="number" class="custom-amount" id='+value.response_code+' placeholder="Rs."></td>');
Depending upon the action there can be any number of input field appended to the div. 根据操作,可以在div上附加任意数量的输入字段。 I want to get the values entered on each field.
我想获取在每个字段上输入的值。 when i tried to to get the value using this approach below, it didn't work out.
当我尝试使用下面的这种方法来获取价值时,它没有奏效。 But when i got the dynamically created id value and used in the place of
$(this)
it worked 但是当我得到动态创建的id值并代替
$(this)
它起作用了
$(document).keyup('.custom-amount',function(){
console.log($(this).val()); //just logging empty
console.log($(this).attr('id')); //Logged undefined
})
but this one works 但是这个有效
$(document).keyup('#100520',function(){
console.log($('#100520').val());//works
console.log($('#100520').val());//works
});
Is there anything wrong with my approach ? 我的方法有什么问题吗?
$(document).on('key-up','.custom-amount',function(){
console.log($(this).val()); //just logging empty
console.log($(this).attr('id')); //Logged undefined
})
Have you tried this? 你有尝试过吗?
$(document).on('keyup', '.custom-amount', function(){
console.log($(this).val());
console.log($(this).attr('id'))
});
Try the following code 试试下面的代码
$('#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>
Calling $(this)
in your handler is working as expected. 在处理程序中调用
$(this)
可以正常工作。 Because you are handling events like this $(document).keyup
your handler is invoked on the document
element and not on the element itself, and therefor this
refers to the document
. 因为您正在处理类似
$(document).keyup
这样的事件, $(document).keyup
您的处理程序是在document
元素而不是元素本身上调用的,因此this
是引用document
。
But when you supply event arg object to your handler function, you can use its property target
which will refer to the element which triggered the event, like this: 但是,当您向处理函数提供事件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.