[英]Alerting an input value gives undefined
This HTML is dynamically appended on button click.此 HTML 在按钮单击时动态附加。 The input value is being returned undefined
in the input event handler.输入值在输入事件处理程序中返回undefined
。 Why is this happening?为什么会这样?
html += '<div class="div-table-col-unit"> <input type="text"/></div>';
$(document).on('input', '.div-table-col-unit', function(event) {
alert(this.value);
});
You attached the input
event to the div
element;您将input
事件附加到div
元素; they do not have a value
to read.它们没有可读取的value
。 You need to bind the event directly to the input
instead:您需要将事件直接绑定到input
:
let html = '<p>Foo</p>'; html += '<div class="div-table-col-unit"> <input type="text" /></div>'; $('body').append(html); $(document).on('input', '.div-table-col-unit input', function(event) { console.log(this.value); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Alternatively you can retain the binding to the div
, but use the target
property of the event to reference the element that actually originated the input
event:或者,您可以保留与div
的绑定,但使用事件的target
属性来引用实际发起input
事件的元素:
let html = '<p>Foo</p>'; html += '<div class="div-table-col-unit"> <input type="text" /></div>'; $('body').append(html); $(document).on('input', '.div-table-col-unit', function(event) { console.log(event.target.value); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.