问题
I am using bootstrap modals and Ruby on Rails. I was able to display the modal fine but I am having trouble using Javascript to manipulate the contents of the modal. I am not sure what I am doing wrong but I was not able to use Javascript to impact the contents of the modal at all, to the point that I started wondering if there are such a thing as different stack levels on the DOM elements or whether even the modal contents are part of the DOM.
Here is my app/views/home/index.haml:
- url = @entry.class.to_s.downcase.singularize
= link_to(send("#{url}_path", @entry), remote: true) do
= yield
#modals
The view contains the link to open up the modal and in this case @entry represents an image object. And in the images controller we have the show action, which I am using to display the modal:
def show
authorize! :view, @image
@can_destroy = can?('delete_asset', @image)
@can_edit = can?('edit_metadata', @image)
respond_to do |format|
format.js
end
end
And for the modal views, I have the app/view/show.js.erb
$("#modals").html('<%= j render "images/modal", image: @image %>');
$('#modals .modal').modal();
$('#modals .modal').modal('.toggle');
And finally, I have the modal partial in app/views/images/_modal.haml
.modal
.modal-dialog
.modal-content
.modal-header
= image_tag(@image.file_original.url(:modal))
.modal-body
#shortdesc.row
.col-md-6
short description: #{@image.description_short}
.col-md-6.rightButton
%a.detailers
%span#toggle-text SHOW
DETAILS
%ul.errors
#detail.details{:style => "display: none"}
%div.modal-details
%i media type:
= @image.media_type
%br/
%div.modal-details
%i subject:
= @image.subject
%br/
%div.modal-details
%i title:
= @image.title
%br/
%div.modal-details
%i full description:
= @image.description
%br/
%div.modal-details
%i location:
= @image.location
%br/
%div.modal-details
%i date:
%br/
%div.modal-details
%i author:
= @image.author
%br/
%div.modal-details
%i source:
= @image.source
%br/
%div.modal-details
%i tags:
= @image.tag_list.join(' - ')
%br/
%br/
%div.modal-detailsgreen This item is shared by
%span.sharedbyfirstname
= @image.user.name_first
%span.sharedbylastname
= @image.user.name_last
%br/
%br/
Now I want to hide and show (toggle) the contents of the div with id= "detail" and class ="details" when the link with class= "detailers" is clicked on. I have tried to write Javascript inside the show.js.erb to manipulate the contents of the modal with no success. Is there a certain place I should put my JS to manipulate the contents of the JS ?
回答1:
$('#modals .modal').on('shown.bs.modal', function () {
// do something…
});
来源:https://stackoverflow.com/questions/39565102/how-to-use-javascript-to-manipulate-modal-content