【问题标题】:How to get 'id' from an open bootstrap modal?如何从打开的引导模式中获取“id”?
【发布时间】:2013-05-23 06:38:18
【问题描述】:

我有一个带有id="<%= p.id %>" 的模态框(模态框内的帖子ID)。我想在模式打开时对它的内容做一些事情(我需要在 .js 文件中这样做)。但是如何从打开的模态中获取 id 到 javascript 中?

我已经尝试过使用下面的javascript代码,但它不起作用。有什么建议吗?

_singlePost.html.erb

<a class="fg" href="#<%= p.id %>" data-toggle="modal">
    <div id="withJosefin">
        <%= p.title %>
    </div>
</a>

<div id="<%= p.id %>" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <p><h3 id="myModalLabel"><%= p.title %></h3></p>
    </div>
    <div class="modal-body">
        <%= raw(p.link) %>
    </div>
</div>

pages.js.coffee

$ ->
  if ('div.modal.hide.in').is(":visible")
    currentId = $('.modal.fade.in').attr('id')
    //Do something with currentId here

【问题讨论】:

  • 我在这里看不到任何 jquery 代码
  • @roasted - 这是撒了 jQuery 的咖啡渣!
  • @adeneo 我不知道,谢谢输入!
  • 这还不够吗:currentId = $('.modal.fade.in').attr('id') 没有 'if' 测试可见。据我了解,引导程序为打开的模式添加类'in',不是吗?
  • @roasted:我认为currentId = $('.modal.fade.in').attr('id') 会起作用,但我需要在打开模式时触发它。所以我想我需要一个if 声明......(但我写的那个不起作用。)

标签: javascript jquery ruby-on-rails twitter-bootstrap coffeescript


【解决方案1】:

documentation

当模态显示如下时,您可以创建回调:

$('#myModal').on('shown', function () {
  // do something…
})

在你的情况下,你会这样:

//Somewhere in the beginning of your coffeescript/javascript before the modal is opened by the user.

//CoffeeScript
$("div.modal.hide").on "shown", ->
    id = $(this).attr('id')
    //Do whatever you want with the id

//javascript
$('div.modal.hide').on('shown', function(){
    var id = $(this).attr('id');
    //Do whatever you want with the id
});

希望有帮助

【讨论】:

  • 请注意,引导程序 3 应使用 on.('shown.bs.modal') 而不是 on.('shown')
  • 如上 - 与 bootstrap 4 相同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 2016-05-09
  • 2017-09-11
  • 1970-01-01
  • 2021-05-05
  • 2015-05-09
相关资源
最近更新 更多