2015-09-24 120 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 
    } 

}