twitter-bootstrap 如何从开放的引导模式中获取“id”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16789547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 17:13:56  来源:igfitidea点击:

How to get 'id' from an open bootstrap modal?

javascriptjqueryruby-on-railstwitter-bootstrapcoffeescript

提问by allegutta

I have a modal with id="<%= p.id %>"(the id of the post that is in the modal). I want to do something with the content of the modal when it is open (and I need to do this in the.js file). But how can I get id from the opened modal into javascript?

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

I have tried with the javascript code under, but it does not work. Any suggestions?

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

_singlePost.html.erb

_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

pages.js.coffee

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

采纳答案by Automatico

Found this in the documentation:

文档中找到了这个:

You can create a callback when the modal is shown like this:

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

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

In your case you would have this:

在你的情况下,你会有这个:

//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
});

Hope that helps

希望有帮助