簡體   English   中英

在頁面加載時加載Javascript

[英]Load Javascript on page load

如何在頁面加載時加載此JavaScript模式? 來自插件“ sweet alert”。 我真的對JavaScript很不好。 任何建議一定會有所幫助!

<script>
$(function () {

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

});

由於您正在使用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>

假設swal()是打開模態的原因,只需將其移動到click事件之外。 一旦單擊了帶有.demo1類的元素,您當前的代碼將僅運行swal()函數。 通過將其移到單擊處理程序函數之外,它可以在頁面准備好后立即運行。

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

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

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

只需添加上面的腳本,這將在頁面加載時觸發您的甜蜜警報。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM