在页面加载时加载Javascript

时间:2017-02-01 04:29:35

标签: javascript jquery html function

如何在页面加载时加载此javascript模式?这是来自插件“甜蜜警报”。我用javascript非常糟糕。任何建议肯定会有所帮助!

<script>
$(function () {

    $('.demo1').click(function(){
        swal({
            title: "Welcome in Alerts",
            text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
        });
    });

});

4 个答案:

答案 0 :(得分:3)

由于您使用的是jquery,因此可以使用document.ready来包装代码

<script>
$(document).ready(function() {
  $('.demo1').click(function() {
    swal({
      title: "Welcome in Alerts",
      text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
    });
  });
})
</script>

现在,如果您将此代码段放在收盘body附近,则可以避免document.ready

<body>
   //rest of the dom element
   <script>
    $('.demo1').click(function() {
        swal({
          title: "Welcome in Alerts",
          text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
        });
      });
    </script>
</body>

答案 1 :(得分:0)

假设swal()打开了你的模态,只需将其移到click事件之外。您的当前代码仅在单击具有swal()类的元素后才运行.demo1函数。通过将其移动到单击处理函数之外,它会在页面准备就绪后立即运行。

$(function() {
    swal({
        title: 'welcome',
        text: 'ding!'
    });
});

答案 2 :(得分:0)

$(function(){
 $('button').click(function(){
   swal("Oops! you clicked me.")
 })

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>



<button>Click me</button>

为了运行sweetalert,您首先需要调用它的资源,并加载jQuery,如下所示。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet"/>
</head>
<body>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
</body>
</html>

$(function(){
  swal("Hi! I'm loaded on doc ready.");
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

答案 3 :(得分:0)

<script>
 $(document).ready(function(){
   swal({
  title: "Welcome in Alerts",
  text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
   });
 });
</script>

只需添加以上脚本,这将在页面加载时触发您的甜蜜警报。