我有一个模态对话框,我尝试使用javvascript的onClick
函数来关闭它,但它说“closeModal未定义'。
这是我的模式的html:
<div id="popup" class="modal-box">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Registration</h4>
</div>
<div class="modal-body">
<p>Modal Body</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick="closeModal()">Close</button>
</div>
</div>
这是我的javascript:
<script type="text/javascript">
$(function closeModal() {
$('#popup').modal('hide');
});
</script>
我无法理解为什么它说未定义因为函数和onClick
具有相同的名称(closeModal
)而我在函数中引用#popup
来关闭整个模态。
答案 0 :(得分:1)
closeModal
应该在全球范围内,$(function (){})
是$(document).ready(function() {})
function closeModal() {
console.log(this);
// $('#popup').modal('hide');
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup" class="modal-box">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Registration</h4>
</div>
<div class="modal-body">
<p>Modal Body</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick="closeModal()">Close</button>
</div>
</div>
&#13;
此外,如果您使用jQuery,您不需要使用内联事件,您可以像这样更改您的示例
$(function () {
$('.js-close-modal').on('click', function () {
console.log(this);
// your code
});
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup" class="modal-box">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Registration</h4>
</div>
<div class="modal-body">
<p>Modal Body</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default js-close-modal" data-dismiss="modal">Close</button>
</div>
</div>
&#13;