首页 > 解决方案 > Correctly usage of vars in javascript

问题描述

How can I use these both scripts on the same page? I'm new in js but I'm pretty sure that I can't use these same vars to make both scripts work correctly after an error (or even more if I want to). "Swal" is a customized alert.

<script>
    window.onload = function(){
         var url = new URL(window.location.href);
         var error = url.searchParams.get("error");

         if(error==1) swal("Oops...", "Primeiro você deve escolher uma foto. Clique no botão 'Alterar Foto'.", "error");
    }
</script>

<script>
    window.onload = function(){
         var url = new URL(window.location.href);
         var error = url.searchParams.get("error");

         if(error==2) swal("Formato Inválido", "Por favor, escolha uma imagem no formato 'PNG' ou 'JPG'.", "warning");
         }
</script>

标签: javascriptvariablesalert

解决方案


不要使用旧的 onload/onclick,如果需要支持 < IE9,请使用 addEventListener 和/或 attachEvent。


推荐阅读