2015-09-24 121 views
0

我試圖針對不同的選項有不同的onload事件。例如:如果我的變量$ var == 1它會觸發一個window.onload事件,並且如果變量$ var == 2,那麼另一個window.onload事件會觸發。 但我的代碼不起作用。我從隱藏的輸入中獲取變量值id='alert'是否有另一種方法來做這種編碼,以及我在這裏做錯了什麼?
THX傢伙IF語句中的不同window.onload事件

這裏是我的代碼

的JavaScript:

<script type="text/javascript"> 

      function Onload(){ 

      var variable=document.getElementById("alert").value; 

      if(variable.value=="1"){ 

       window.onload = function() 
       { 
        swal({ 
        title: "Example", 
        text: "Example123!", 
        type: "success", 
        showCancelButton: false, 
        confirmButtonClass: 'btn-success', 
        confirmButtonText: 'Close' 
        }); 
       }; 

      } 
      if(variable.value=="2"){ 
       window.onload = function() 
       { 
        swal({ 
        title: "Example", 
        text: "Example1234", 
        type: "error", 
        showCancelButton: false, 
        confirmButtonClass: 'btn-danger', 
        confirmButtonText: 'Close' 
        }); 
       }; 
      } 
      if(variable.value=="3"){ 

       window.onload==function(){ 

        false; 

       } 

      } 

      }  

</script> 

HTML

<body onLoad='Onload();'> 
<input type='hidden' id='alert' name='alert' value="<?php echo $alert; ?>"> 

回答

1

有沒有必要使用隱藏的輸入時,你可以把你的變量直接進入<script>部分與json_encode。例如:

<script type="text/javascript"> 
(function() { // grouping the code into IIFE to prevent global scope pollution 
    var modalIndex = <?php echo json_encode($alert); ?>; 
    var modalOpts = { 
    1: { 
     title: 'Example1', 
     text: 'Example1234', 
     type: 'success', 
     showCancelButton: false, 
     confirmButtonClass: 'btn-success', 
     confirmButtonText: 'Close' 
    }, 
    2: { 
     title: 'Example2', 
     text: 'Example2341', 
     type: 'warning', 
     showCancelButton: false, 
     confirmButtonClass: 'btn-danger', 
     confirmButtonText: 'Close' 
    }, 
    }; 
    if (modalIndex in modalOpts) { 
    window.onload = function() { 
     swal(modalOpts[modalIndex]); 
    } 
    } 
})(); 

注意,I 1)中除去Onload功能,從而使代碼將被立即執行; 2)將選項分組爲單個對象; 3)對服務器設置的配置段的存在進行了臨時檢查。

+0

它的工作原理非常好,非常感謝。 – MadMaxa

0

window.onload觸發您Onload功能。在該函數中再次分配它將不會重新觸發它。相反,只需要直接調用這些函數:

function Onload() { 
    var variable = document.getElementById("alert").value; 
    if (variable == "1") { 

     swal({ 
      title: "Example", 
      text: "Example123!", 
      type: "success", 
      showCancelButton: false, 
      confirmButtonClass: 'btn-success', 
      confirmButtonText: 'Close' 
     }); 
    } 
    if (variable == "2") { 

     swal({ 
      title: "Example", 
      text: "Example1234", 
      type: "error", 
      showCancelButton: false, 
      confirmButtonClass: 'btn-danger', 
      confirmButtonText: 'Close' 
     }); 

    } 
    if (variable == "3") { 
     //just do nothing 
    } 

}