【问题标题】:How to show/hide div using ajax?如何使用ajax显示/隐藏div?
【发布时间】:2020-09-07 17:07:26
【问题描述】:

目前我可以单击按钮获取数据并显示带有评论回复的 div,就像在 Youtube 上一样,但我想通过再次单击使其消失。这样可以吗?

$(document).ready(function () {
    $(".showReplies").click(function () {
        let id = $(this).attr('id');
        $.ajax({
            url: $(this).attr("data-href"),
            type: 'get',

            success: function (data) {
                console.log(data);
                console.log(id)
                $(`#${id}.replies`).html(data);
            }
        })
    });
});

我尝试添加 display: none 然后将其更改为阻止,或设置 value='show/hide' 然后使用 toggle('show') 但它不起作用。感谢您提前提供任何帮助。

【问题讨论】:

  • 您可以在点击监听器的第一行添加`$(#${id}.replies).html(''");`?
  • 就在$(".showReplies").click(function () { 的下方?没有帮助。
  • let id = $(this).attr('id'); 之后。好吧,我添加了一个小例子。

标签: javascript html ajax


【解决方案1】:

$(document).ready(function () {
  $(".showReplies").click(function () {
      let id = $(this).attr('data-id');
      $(`#${id} .replies`).html("Loading..");

      setTimeout(() => {
        $.ajax({
          url: `https://jsonplaceholder.typicode.com/todos/${id}`,
          type: 'get',
          success: function (data) {
              $(`#${id} .replies`).text(JSON.stringify(data));
          }
        })
      }, 1000);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="1">
  <div class="replies"></div>
  <button class="showReplies" data-id="1">Load Replies</button>
</div>


<div id="2">
  <div class="replies"></div>
  <button class="showReplies" data-id="2">Load Replies</button>
</div>

【讨论】:

  • 感谢您的尝试,但在您的示例中,再次单击按钮后数据并没有消失,这就是我想要实现的目标。
  • 代码就好了。我使用的 API 太快了,加载也太快了。我已经使用 setTimeout 在代码中引入了延迟,现在您应该可以看到更改发生了。
  • 再次:我有按钮“显示回复”,当我点击它时,回复显示在 div 中,让我们说按钮更改为“隐藏回复”,当我再次点击它时,div 消失并且按钮是再次“显示回复”。我希望你理解,也许知道解决方案:)
  • 我找到了一种解决方案。我在let id = $(this).attr('id'); 正下方添加了$(#${id}.replies).toggle();,但我还有另一个问题:当我先单击按钮时,控制台会打印数据但 div 不会立即显示。在我再次单击它之前,它会正确显示和隐藏。
【解决方案2】:

这是一个示例,但您的代码看起来有误。这对我来说没有意义。

beforeSend: function(data) { 
                $("#hideID").hide();
           },              
           success: function (data) {
            console.log(data);
            console.log(id)
            $(`#${id}.replies`).html(data);
        }

【讨论】:

  • 您认为有什么问题?我找到了一种解决方案。我添加了 $(#${id}.replies).toggle();就在let id = $(this).attr('id');下面,但我还有另一个问题:当我先点击按钮时,控制台打印数据但div没有立即显示。在我再次单击它之前,它会正确显示和隐藏。
猜你喜欢
  • 2014-05-22
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-03
相关资源
最近更新 更多