我有一个带有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
答案 0 :(得分:2)
当模态显示如下时,您可以创建一个回调:
$('#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
});
希望有所帮助