首页 > 解决方案 > 由 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>

标签: javascripthtmljquerydom

解决方案


A 认为我看到了你的问题。

当一个文档(网页)加载时,特定的目标 jQuery 函数就像你的..

$(".validate").click( function() {

   // ...

});

// and...

$(".lieu").on("mouseenter", function() {

   // ...

});

..只会在文件准备好时绑定,而不是因为你在里面使用这些$(document).ready(function()。所以当 doc 准备好时,上面 2 个函数运行并绑定。

像您在 doc ready 中那样运行函数是一种很好的做法。

但是,如果您打算将现有执行的函数自动绑定到新添加的文档元素..那么您的前 2 个函数超出了范围。

您需要查看.on() https://api.jquery.com/on/

例如,如果您希望新添加的文档元素(如.lieudiv)被您的mouseover函数击中,那么您可以使用.on这样的函数...

$(document).on("mouseenter", ".lieu", function()

第二.on()个参数是.lieu选择器,$(document)作为主要的 jQuery 选择器对象。

这意味着如果您将任意数量的新.lieudiv 附加到documenthtml,则在其中使用.on()选择器参数$(document)将始终在此选择器上的 mouseover 事件的范围内。


推荐阅读