使用Javascript在HTML中处理事件

3

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

我尝试在HTML文件中使用<script></script>,它可以正常工作,但是我想在单击HTML中的按钮时使用JavaScript文件进行触发。

以下是代码: HTML中的JavaScript代码放在<head></head>标签中:

<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>

1
您似乎没有包含jQuery,但正在使用jQuery方法。 - Obsidian Age
@ObsidianAge 您是什么意思?您能帮助我处理它吗? - Ban Tot
这个 <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> 是不是在 index.js 里面? - Ele
2
@AlexAbulencia 在你的 HTML 文件中,在 <script src="jsFiles/index.js"></script> 的上方加入 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>,然后再试一下。如果不包含 jQuery,它是无法工作的,这就是 Obsidian Age 所说的。 - Aniket G
1
@AniketG。好的,先生。我会尝试的。 - Ban Tot
显示剩余7条评论
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',
          }
        }
      });

  });
});

谢谢您先生!您和@Aniket G帮了我很多。谢谢。 - Ban Tot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接