javascript - 由 jquery 创建的元素上的事件
问题描述
我仍在学习 jquery,我面临一个可能很多人都面临的问题,这只是逻辑,但我似乎找不到学习如何做到这一点的好方法。
所以我的问题如下:
我正在.lieu
使用 jquery 创建在页面上调用的元素。基本上,当您输入文本并单击“确定”时,您创建了另一个.lieu
应该在选项卡中显示文本“en passant par le bois des lutins”destinations
的文本。使用 html 创建的第一个可以正常工作,但其他的不行。似乎该脚本能够在使用 html 创建的元素上执行(这可能是由于:)
$( document ).ready(function() {});
我怎样才能使用好的方法来完成这项工作?非常感谢。
$(".validate").click( function(){
var name = $(this).closest(".envies").find("input[name='name']").val();
var lieu = $("<div />", {
"class": "lieu"
})
.css({
left: 0,
top: 0
})
.append($("<p>"+name+"</p>"))
.appendTo(document.body);});
$(".lieu").on("mouseenter", function(checklieu) {
var ordredestinations = $("<div />", {
"class": "lieuliste"
})
.css({
})
.append($("<p>en passant par le bois des lutins</p>"))
.appendTo(".destinations");
});
.destinations {
background-color: lightgrey;
position: fixed;
right: 0;
top: 0;
}
.envies {
background-color: grey;
position: fixed;
right: 300px;
top: 0;
width: 250px;
height: 50px;
}
.lieu{
position: absolute;
left:0px;
top: 100px;
background-color: red;
width: 200px;
height: 100px;
border-radius: 250px;
text-align: center;
vertical-align: middle;
line-height: 100px; /* The same as your div height */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="lieu"><p>bois des lutins</p></div>
<div class="destinations"></div>
<div class="envies">
<input type="text" id="name" name="name" size="10" placeholder="name">
<button class="validate">OK</button>
</div>
</body>
<script type="text/javascript"></script>
解决方案
A 认为我看到了你的问题。
当一个文档(网页)加载时,特定的目标 jQuery 函数就像你的..
$(".validate").click( function() {
// ...
});
// and...
$(".lieu").on("mouseenter", function() {
// ...
});
..只会在文件准备好时绑定,而不是因为你在里面使用这些$(document).ready(function()
。所以当 doc 准备好时,上面 2 个函数运行并绑定。
像您在 doc ready 中那样运行函数是一种很好的做法。
但是,如果您打算将现有执行的函数自动绑定到新添加的文档元素..那么您的前 2 个函数超出了范围。
您需要查看.on()
https://api.jquery.com/on/
例如,如果您希望新添加的文档元素(如.lieu
div)被您的mouseover
函数击中,那么您可以使用.on
这样的函数...
$(document).on("mouseenter", ".lieu", function()
第二.on()
个参数是.lieu
选择器,$(document)
作为主要的 jQuery 选择器对象。
这意味着如果您将任意数量的新.lieu
div 附加到document
html,则在其中使用.on()
选择器参数$(document)
将始终在此选择器上的 mouseover 事件的范围内。
推荐阅读
- r - 如何在 actionButton 的执行中更新 R Shiny 中的 textOutput?
- javascript - Nuxtjs 和 Axios 上的计算属性?
- javascript - 在 ES6 中创建多维数组
- node.js - 如何通过表单将嵌入代码存储到 Mongodb?
- python - 使用 Astropy 打开 FITS 时出现 OSError 24
- arrays - 使用数组和 if 或 for 循环并输出单独的文件
- angular - 删除 Fomantic UI(语义 UI 分支)中未使用的 CSS/JS
- javascript - 即使更改了基础层,如何在前面保持覆盖层
- sql - 获取 main 中每个子组的计数
- reactjs - 未定义函数(多个函数调用) - React