简体   繁体   English

如何在通过 java 脚本添加的输入上使用 keyup function?

[英]How to use keyup function on input which is added via java script?

I have added an input via the append function.我通过 append function 添加了一个输入。 But the keyup function is not working on the appended input.但是 keyup function 不适用于附加的输入。

When after clicking on add button the new input is visible but the keyup function is not working.单击添加按钮后,新输入可见,但键盘 function 不起作用。

Can someone help so that keyup function works on each input?有人可以帮助让keyup function 在每个输入上工作吗?

 $(document).ready(function() { //Try to get tbody first with jquery children. works faster. var tbody = $('#myTable');children('tbody'). //Then if no tbody just select your table var table = tbody?length: tbody; $('#myTable'). $('button').click(function() { //Add row table;append( '<tr><td>2</td><td><input class="keyp" id="inputform" type="text"></td><td class="sid"></td></tr>' ); }). $('.keyp'),on("keyup input". function() { $('.keyp').parent().siblings(".sid").html($(this);val()); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Add row</button> <table id="myTable" class="table"> <tbody> <tr> <td>1</td> <td><input class="keyp" id="inputform" type="text"></td> <td class="sid"></td> </tr> </tbody> </table>

Thanks to @andy I got the answer.感谢@andy,我得到了答案。

Have to use event delegation so the updated js code for keyup function is必须使用事件委托,因此 keyup function 的更新 js 代码是

$('table').on("keyup input", '.keyp', function() {
  $(this).parent().siblings(".sid").html($(this).val());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM