简体   繁体   English

html到js文件中的javascript代码

[英]javascript code in html to js file

I am struggling with the following problem. 我正在努力解决以下问题。

I have made a memorygame with javascrpt for school.It all works fine, but my teacher told me that i can not have on line of javascript in my HTML, like this : 我已经在学校用javascrpt制作了一个记忆游戏,一切都很好,但是我的老师告诉我,我的HTML中无法使用javascript,就像这样:

HTML : HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="styles.css">
        <title>Memory spelen</title>
    </head>
    <body>
        <script type="text/javascript" src="javascript.js"></script>
        <div id="memory_board"></div>
        <script>newBoard();</script>
   </body>
</html>

The newBoard() is applied to the memory_board div. newBoard()应用于memory_board div。 How can i take this little piece of script out of my HTML file and place it in my js file, to still function properly. 我如何才能将这小段脚本从HTML文件中取出并放在js文件中,以使其仍然正常运行。

Thanks in advance 提前致谢

Inside of your javascript.js put this 在您的javascript.js里面放这个

window.onload = function {

    // content of your script

    var newBoard = function(){
        // the new updated newBoard() function from below
    }

    // other parts of your script

    if(window.location.href == 'your-url') {
        // now, after the newBoard() has been updated
        // the next to lines are not needed 
        // var board = document.getElementById('memory_board');            
        // board.innerHTML = newBoard();
        // just call the function
        newBoard();
    }
};

UPDATE UPDATE

I just took a look at your old fiddle and I changed your newBoard function to this 我只是看了看您的旧提琴,然后将newBoard函数更改为

function newBoard(){
    tiles_flipped = 0;
    var output = '';
    memory_array.memory_tile_shuffle();
    for(var i = 0; i < memory_array.length; i++){
        var div = document.createElement('DIV');
        div.id =  "tile_" + i;
        (function(div,i){
            div.onclick = function() {
                memoryFlipTile(this, memory_array[i]);
            };
        }(div,i));
        document.getElementById('memory_board').appendChild(div);
    }
}

Check the working fiddle . 检查工作提琴

try to put it like this in external js file 尝试将其放在外部js文件中

$(document).ready(function(){
   newBoard();
});

看来您需要在memory_board div的onload事件上调用newBoard()方法,可以通过以下方式进行操作:

<div id="memory_board" onload="javascript:newBoard()"  ></div>  // use onload event of memory_board

you can use onload function on the javascript. 您可以在javascript上使用onload函数。 It will call the function when all the HTML tag is loaded on the screen. 当所有HTML标记加载到屏幕上时,它将调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM