【问题标题】:jquery append and not being able to click the appended classjquery append 并且无法单击附加的类
【发布时间】:2017-06-16 01:29:03
【问题描述】:

我有一个 div,当点击一个新的 div 时,它会被附加 - 当这个新的 div 显示并希望通过点击它来关闭它时,它会触发。

这是我的小提琴

https://jsfiddle.net/foba81eb/

$(document).ready(function() {
    var counter = 0;
    $('.one').click(function() {
    if (counter <= 0) {
        $('p').append("<p id='closingCross'>X</p>");
        counter++;
    }
});
  $('#closingCross').click(function() {
    //This is not firing?!
    alert("hello");
  });
});

我只想让它在点击时关闭,但它什么也没做?

我在这里做错了什么?

干杯,

本。

P.S - 看看更新的小提琴

https://jsfiddle.net/foba81eb/4/

当我 .hide() 然后单击以将其取回时,它不起作用!

【问题讨论】:

  • 我还没有发现可以这样做,因为当文档准备好时,动态内容还不存在。尝试让内容存在但隐藏它。 (CSS显示:无)
  • 改为写$(document).on("click", "#closingCross", function() {..

标签: jquery onclick append


【解决方案1】:

HTML:

<div class="one">
<p>
hello world
</p>
<p id='closingCross' style="display:none">X</p>

</div>

JS:

$(document).ready(function(){


var counter=0;

$('.one').click(function() {
if(counter <= 0){
  $('p').show();
  counter++;
}
 });

$('#closingCross').click(function() {
    alert("hello");
 });


});

【讨论】:

    【解决方案2】:

    使用delegated event handler

    变化:

    $('#closingCross').click(function() {
    

    到:

    $(document).on('click', '.closingCross', function(e) {
    

    sn-p:

    $(document).on('click', '.closingCross', function(e) {
      console.log("hello");
    });
    
    
    $(document).ready(function(){
    
      var counter=0;
    
      $('.one').click(function() {
        if(counter <= 0){
          $('p').append( "<p class='closingCross'>X</p>" );
          counter++;
        }
      });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <div class="one">
        <p>
            hello world
        </p>
    
    
    </div>

    【讨论】:

    • 请查看我在 fiddle 上的更新版本 - jsfiddle.net/foba81eb/4 仍然无法重新打开!为帮助干杯!
    • @user3502952 你能解释一下你打算重新打开什么吗?
    • 我想为我的网站创建一个覆盖菜单系统。用户单击汉堡包图标,然后 meun / overlay 出现 X,然后您单击将删除它的那个 - 这有意义吗?
    • 我以这个为例,但我想覆盖整个屏幕badassembly.com谢谢!
    【解决方案3】:

    您需要做的就是将事件附加到 DOM 中已创建的元素。

    $('#topp').on('click', 'p', function() {
        alert("hello");
     });
    

    您的工作示例: https://jsfiddle.net/foba81eb/4/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 2012-10-01
      • 2023-04-05
      相关资源
      最近更新 更多