【问题标题】:Onclick closing a DIV loaded with ajaxOnclick 关闭加载了 ajax 的 DIV
【发布时间】:2016-06-02 19:48:26
【问题描述】:

我正在以这种方式在 wordpress 网站上使用 ajax 加载我的内容:

<script>
   $(document).ready(function(){
        $.ajaxSetup({cache:false});
        $(".post-link").click(function(){
            var post_link = $(this).attr("href");

        $("#single-post-container").show().html("content loading");
        $("#single-post-container").load(post_link);
        return false;
        });

    });
</script>

这很好用,但是当我尝试向按钮添加功能以关闭此 DIV 时,没有任何反应:

<script>
    $("#hide").click(function(){
        $("#single-post-container").hide();
    });
</script>

所以首先我做“显示”,然后我想用“隐藏”关闭它,但它不起作用,无论按钮是在 ajax 加载的 DIV 内部还是外部。

【问题讨论】:

  • 隐藏ID的按钮在哪里?如果是动态加载的,需要找一个 MANY 事件委托答案
  • 按钮在加载的DIV里面。我什至不能用 jquery 向加载的 DIV 添加一个类...... .
  • 查看我的更新评论。按钮是否在加载的html中会有很大的不同
  • 按钮在加载的DIV之外甚至不起作用。
  • 这不太可能。发布 html 并显示您分配点击处理程序的位置

标签: jquery html ajax


【解决方案1】:

您尚未发布 HTML,但必须满足以下条件:

  1. ID 为 single-post-container 的内容在页面加载时必须存在,并且只有其中一个(唯一 ID)
  2. ID 为 hide 的内容在页面加载时必须存在,并且只有其中之一
  3. 按钮必须有type="button",否则它会尝试将页面提交给自己

如果是1而不是2,并且hide被加载到你需要的容器中

$(function(){
  $.ajaxSetup({cache:false});
  $(".post-link").on("click",function(e){
    e.preventDefault();
    var post_link = $(this).attr("href");
    $("#single-post-container").show().html("content loading");
    $("#single-post-container").load(post_link);
  });
  $("#single-post-container").on("click","#hide",function(){
    $("#single-post-container").hide();
  });
});

如果 1 AND 2 和 hide 在容器外:

$(function(){
  $.ajaxSetup({cache:false});
  $(".post-link").click(function(e){
    e.preventDefault();
    var post_link = $(this).attr("href");
    $("#single-post-container").show().html("content loading");
    $("#single-post-container").load(post_link);
  });
  $("#hide").on("click",function(){
    $("#single-post-container").hide();
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    相关资源
    最近更新 更多