模态未定义错误

时间:2017-03-21 13:55:01

标签: javascript jquery twitter-bootstrap

jQuery Cide:

function modal(this) {
        alert($(this).data("id"));
    }

HTML代码:

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-id="<?php echo $state['ID']?>" onclick='modal(this)'>Open Modal</button>

Bootstrap Modal

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

错误:

Uncaught ReferenceError: modal is not defined at HTMLButtonElement.onclick

我已经在文档就绪函数之外定义了模态,但它显示的模态未定义错误如何解决此错误?

2 个答案:

答案 0 :(得分:0)

这是工作片段。

function modal(ref) {
	alert($(ref).data("id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-id="1" onclick='modal(this)'>Open Modal</button>

答案 1 :(得分:0)

阅读本文:Why can't I use onClick to execute a function inside a jQuery $(document).ready function?

  1. 为按钮添加ID:id="btnModal"

  2. 删除此内容:onclick='modal(this)'

  3. 把它放在document.ready之外):

    $('#btnModal' ).click(function() 
     {
        $('#myModal').modal('show');
     });