为什么不调用这个JavaScript函数?

时间:2014-05-07 23:25:05

标签: javascript function

我有这个函数,据说可以读取和解析url变量:

function parseError(){
    //get url vars and convert them into javascript vars
    function get(){var vars={};var parts=window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value){vars[key]=value;});return vars;}
    var err_type=get()["t"];
    var err_code=get()["c"];
    var redirect=get()["redirect"];

    //set message based on var data
    var extension = "Hello!";
    if(err_type=1)extension="<a href="+redirect+"><button class=\"dismiss\">Dismiss</button></a>";
    if(err_code=0)err_msg="This site has detected that you currently have javascript turned off. To view this site, you must enable javascript.";
    if(err_code=0)err_msg="When you have javascript enabled, <a href="+redirect+">click here.</a>";

    //write messages to elements
    document.getElementById("err_msg").innerHTML=err_msg;
    document.getElementById("err_sub").innerHTML=err_msg;
    document.getElementById("err_ex").innerHTML=extension;
}

我也有这些元素:

<body onLoad="parseError();">
<div id="err" align="center">

<div id="err_msg">Loading...</div>
<div class="error_sub">:)</div>
<div class="error_ex"></div>

</div>
</body>

似乎这个功能甚至没有被调用。

很抱歉这是很多代码,但我不确定函数中的一个小错误是否影响了整个工作。非常感谢帮助。

1 个答案:

答案 0 :(得分:-1)

在函数中初始化变量err_msg

function parseError(){
    //get url vars and convert them into javascript vars
    function get(){var vars={};var parts=window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value){vars[key]=value;});return vars;}
    var err_type=get()["t"];
    var err_code=get()["c"];
    var redirect=get()["redirect"];
    var err_msg="";
    //set message based on var data

    var extension = "Hello!";
    if(err_type=1)extension="<a href="+redirect+"><button class=\"dismiss\">Dismiss</button></a>";
    if(err_code=0)err_msg="This site has detected that you currently have javascript turned off. To view this site, you must enable javascript.";
    if(err_code=0)err_msg="When you have javascript enabled, <a href="+redirect+">click here.</a>";

    //write messages to elements
    document.getElementById("err_msg").innerHTML=err_msg;
    document.getElementById("err_sub").innerHTML=err_msg;
    document.getElementById("err_ex").innerHTML=extension;
}

调整您的选择器,它是ID而不是Class:

<div id="err" align="center">

<div id="err_msg">Loading...</div>
<div  id="err_sub">:)</div>
<div id="err_ex"></div>

</div>

DEMO: http://jsfiddle.net/abdennour/447zF/