一个相当简单的问题——为什么鼠标悬停不触发页面加载后动态生成的(文本)输入?
我可以让它工作的复选框,选择,文本区…
下面的代码没有给出事件
$(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">
下面的代码给出了一个事件,除了文本输入:
$(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>
如何触发鼠标悬停事件的文本输入?
编辑:文本输入是在文档加载后动态生成的。
谢谢
您需要向.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>