[英]How to close & open a modal like Bootstrap
I want to create a modal like Bootstrap ... I have wrote this codes : 我想创建一个类似Bootstrap的模态...我写了这段代码:
<button type="button" data-target="#myModal" class="btn btn-primary">Open Modal</button>
<div class="modal fadeIn" id="myModal">
<div class="modal-header">
Roj Framework <span class="close-btn">×</span>
</div>
<div class="modal-content">
Hi, This Roj Framework !
</div>
<div class="modal-footer">
Continue ...
</div>
</div>
But I have a problem in understanding how to close & open it. 但是我在理解如何关闭和打开它时遇到了问题。 I put a data-target for button to match with Modal Box ID & I don't display the modal from the beginning ..., So I wrote this code but It doesn't work ...
我把按钮的数据目标与Modal Box ID匹配,我从一开始就不显示模态...,所以我写了这段代码,但它不起作用......
$('.modal').css('display', 'none');
$('button').click(function(){
var boxID = $(this).data('target');
var modalBox = $('.modal');
var modalBoxAttr = modalBox.attr('id');
if('boxID' == 'modalBoxAttr') {
modalBox.css('display', 'block');
}
});
There a few mistakes with your code. 你的代码有一些错误。
Mistake 1: 错误1:
Here: 这里:
if('boxID' == 'modalBoxAttr')
You are currently checking the strings
and not the objects
. 您当前正在检查
strings
而不是objects
。 What you have written is the following: 你写的是以下内容:
If the string "boxId" is equal to the string "modalBoxAttr" do something. 如果字符串“boxId”等于字符串“modalBoxAttr”做某事。 And both strings are not the same, so you get a
false
result. 两个字符串都不一样,所以你得到一个
false
结果。
Mistake 2: 错误2:
You are complicating the code too much. 你太复杂了代码。
You can just simplify it like this. 你可以像这样简化它。
$('button').click(function(){ var boxID = $(this).data('target'); var boxObject = $(boxID); if(boxObject.length) { boxObject.toggle(); } });
.modal { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button" data-target="#myModal" class="btn btn-primary">Open Modal</button> <div class="modal fadeIn" id="myModal"> <div class="modal-header"> Roj Framework <span class="close-btn">×</span> </div> <div class="modal-content"> Hi, This Roj Framework ! </div> <div class="modal-footer"> Continue ... </div> </div>
Use more often console.log()
to debug your code and check if you are actually entering a specific section and if your logic is correct. 通常使用
console.log()
来调试代码并检查您是否实际输入了特定部分以及逻辑是否正确。
Try following approach. 尝试以下方法。
Remove data-target="#myModal" from button
从按钮中删除data-target =“#myModal”
<button type="button" class="btn btn-primary">Open Modal</button>
Button click: 按钮点击:
$('button').click(function(){
$("#myModal").modal('show');
}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.