2

我有一个与id="<%= p.id %>"(在模式中的帖子的ID)的模态。我想在模式打开的时候使用模式的内容(并且我需要在.js文件中执行此操作)。但是,我怎样才能从打开的模态id到JavaScript?如何从开放引导模式获得'id'?

我已经尝试使用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 
+0

我看不出有任何的jQuery代码在这里 –

+0

@roasted - 它与jQuery coffeecrap撒! – adeneo

+0

@adeneo我不知道,thx的输入! –

回答

2

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

希望帮助

+0

YES!谢谢!它的工作:) – allegutta

+2

请注意,您应该使用'on。('shown.bs.modal')'而不是'('显示')'引导程序3 – HussienK