Javascript - 功能未定义

时间:2015-11-13 11:29:46

标签: javascript jquery modal-dialog

我有一个模态对话框,我尝试使用javvascript的onClick函数来关闭它,但它说“closeModal未定义'。

这是我的模式的html:

<div id="popup" class="modal-box">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</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来关闭整个模态。

1 个答案:

答案 0 :(得分:1)

closeModal应该在全球范围内,$(function (){})$(document).ready(function() {})

的简写

&#13;
&#13;
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">&times;</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;
&#13;
&#13;

此外,如果您使用jQuery,您不需要使用内联事件,您可以像这样更改您的示例

&#13;
&#13;
$(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">&times;</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;
&#13;
&#13;