3

如何使用 javascript 在 HTML 中触发按钮?

我尝试使用<script></script>HTML 文件,它工作得很好,但是我想在单击 HTML 中的按钮时使用 javascript 文件来触发。

这是代码: HTML<head></head>标记中的 JAVASCRIPT:

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js">
<script src="jsFiles/index.js"></script>

HTML:

             <div class="dropdown-menu">
              <a class="dropdown-item" href="#">Message</a>
              <a class="dropdown-item" href="#">Settings</a>
              <a class="dropdown-item" id="a_id">Log Out</a>
              </div>

JAVASCRIPT 文件:

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    $(document).ready(function(){
        $("#a_id").click(function(){

            swal({title:'Logout', 
            text:'Do you want to logout this Account?', 
            icon:'warning', 
            buttons: true, 
            dangerMode: true
            })
            .then((willOUT) => {
                if (willOUT) {
                    window.location.href = 'page-logout.php', {
                    icon: 'success',
            }
            }
            });

            });
    });
</script>
4

1 回答 1

2

您应该删除所有不是 javascript 代码的内容,因此您的文件index.js应如下所示:

$(document).ready(function() {
  $("#a_id").click(function() {

    swal({
        title: 'Logout',
        text: 'Do you want to logout this Account?',
        icon: 'warning',
        buttons: true,
        dangerMode: true
      })
      .then((willOUT) => {
        if (willOUT) {
          window.location.href = 'page-logout.php', {
            icon: 'success',
          }
        }
      });

  });
});
于 2019-03-12T01:48:38.337 回答