【问题标题】:Twitter Bootstrap Modal change Content via AjaxTwitter Bootstrap Modal 通过 Ajax 更改内容
【发布时间】:2015-03-20 07:55:40
【问题描述】:

我知道,这里有很多相同主题的问题。 但我找不到我的问题的解决方案。 所以我有一个布局,在 body 标签关闭之前有模态窗口:

<!-- Modal -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
              </div>
              <div class="modal-body">
                CONTENT
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
              </div>
            </div>
          </div>
        </div>
    </body>

我的网站中有一个链接可以切换模式窗口:

<a data-toggle="modal" class="btn btn-info" href="myRemote.php?id=1" data-target="#myModal">Click</a>

我的远程 php 只包含“&lt;php echo $_GET['id'];?&gt;”用于测试。 将来会有来自数据库的内容。

所以每次我点击模态的链接时,内容都会改变。 这不是问题,我知道如何在 php 等中做到这一点。

而且我写的 JS 应该改变模态内容:

$(document).ready(function() {
        // Fill modal with content from link href
        $("#myModal").on("show.bs.modal", function(e) {
            var link = $(e.relatedTarget);
            $(this).find(".modal-body").load(link.attr("href"));
        });
    })

问题:

当我单击链接时,模式窗口会打开。完美的。 但是,模式窗口消失了,并且在我的网站的顶部位置有“1”。但这不是很好,因为我只希望 modal-body 中的内容“CONTENT”应该更改为“1”。 我在这里做错了什么?

还有 - 另一个问题。如果我每次都使用 $_GET['id'] 更改内容,那么 1 永远不会消失,但我想在这里更改内容动态,所以在这个例子中,modal-body 类中应该有一个“2”如果我点击这样的链接,模式窗口:

<a data-toggle="modal" class="btn btn-info" href="myRemote.php?id=2" data-target="#myModal">Click</a>

有人可以帮帮我吗?

【问题讨论】:

  • 请创建一个jsfiddle?
  • 您不想使用 ajax 而不是使用 href,然后在 ajax 回调中修改模态的正文?

标签: javascript jquery ajax twitter-bootstrap bootstrap-modal


【解决方案1】:

制作如下链接:

<a class="btn btn-info openModal" data-href="myRemote.php?id=1">Click</a>
<a class="btn btn-info openModal" data-href="myRemote.php?id=1">Click 2</a>

在 Js 上:

$(document).ready(function() {
        // Fill modal with content from link href
        $(".openModal").on("click", function(e) {
            var link = $(this).data("href");
        $('#myModal').modal("show");
        $('#myModal .modal-body').load(link );

        });
    })

你可以试试吗?

【讨论】:

  • 哦,是的,这行得通!谢谢!所以唯一的小问题是,如果我再次点击链接,我首先会看到旧值“1”,然后内容将加载新值,并变为“2”。我有可能避免这种情况吗?
  • 先去掉$('#myModal .modal-body').html("");
  • 小错字$('#myModal).modal("show"); 应该是$('#myModal').modal("show");
猜你喜欢
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 2012-11-14
相关资源
最近更新 更多