简体   繁体   English

如何处理 jQuery 中动态添加元素的事件

[英]How to handle events on dynamically added elements in jQuery

A fairly straightforward question - Why doesn't mouseover trigger for (text) inputs which are dynamically generated after the page has loaded?一个相当简单的问题 - 为什么鼠标悬停不会触发页面加载后动态生成的(文本)输入?

I can get it to work for checkbox, select, textarea...我可以让它为复选框工作,select,textarea ...

Below code doesn't give an event下面的代码没有给出事件

 $(document).ready(function () { $(`input[type=text]`).on(`mouseover`, function (e) { console.log(e); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text">

Below code gives an event for everything but text input:下面的代码为除文本输入之外的所有内容提供了一个事件:

 $(document).ready(function () { $(`input, textarea, [type=checkbox], select`).on(`mouseover`, function (e) { console.log(e); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input> <textarea></textarea> <input type="checkbox"> <select> <option>test</option> </select>

How can I trigger mouseover event for a text input?如何触发文本输入的鼠标悬停事件?

EDIT: The text inputs are dynamically generated after the document has loaded.编辑:文本输入是在文档加载后动态生成的。

Thank you谢谢

You need to pass a second parameter to .on that allows for event delegation :您需要将第二个参数传递给.on以允许事件委托

 $(document).ready(function () { // Set the handler up on something you know will be there from the start // that the event(s) that get triggered later can "bubble" up to. That's // document in this case. // The second argument becomes what you want the event to be handled on $(document).on(`mouseover`, "input[type='text']", function (e) { console.log(e); }); // Create a new element after the handler has been set up $(document.body).append('<input type="text">'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

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