0

我第一次点击按钮,什么都没有。第二次点击代码运行。我在 chrome 或 IE 中运行页面 test.html,没关系。如何获取加载脚本中的代码以运行第一次单击?我是一个js菜鸟。

/* test.html */
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>start</title>
  <script type="text/javascript" src="t01.js">
</script>
</head>
<body>
   <input type="text" id="txt1" />
        <input type="button" id="submit" onclick="getSent(document.getElementById('txt1').value)"
            value=" OK " />
    <div id="reply">reply</div>
</body>
</html>


/* t01.js */
window.onload = function () {
}
function getSent(str) {
    while (1) {

        load_script("relg.js");
        dof();

        reply = "Reached end of loop.";
        break;
    } // end main loop
    document.getElementById("reply").innerHTML = reply;

}
function load_script(filename){
  var fileref=document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", filename);
  if (typeof fileref!="undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref);
}

/* relg.js */
function dof() {
    alert("b");
}
4

1 回答 1

0

脚本需要一些时间来加载,试试这样的:

function getSent(str) {
    load_script("relg.js");
    return; 
}
function load_script(filename){
    var fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.onload = function () {
        dof();
        return;
    }
    fileref.setAttribute("src", filename);
    document.getElementsByTagName("head")[0].appendChild(fileref);
}

另一种选择是创建一个 IIFE(立即调用函数表达式)到regl.js,而不是dof()在主脚本中调用:

(function dof() {
    alert("b");
}());

现在dof()将在解析到页面后立即执行。

于 2013-02-13T18:03:25.723 回答