【问题标题】:passing parameter in onLoad funtion (html and js)在 onLoad 函数中传递参数(html 和 js)
【发布时间】:2015-09-13 16:34:07
【问题描述】:

我正在尝试制作井字游戏,我有 2 个按钮(单人游戏和 2 个玩家),我需要传递一个 int 供用户选择(取决于选择的按钮)并更改我的 js 中的值,
我的html:

<body onload="startGame(i);">   //this is the parameter i want to use
      <table>
           // code......
      </table>

      </br>
      <div id= "menu" class="animated bounceInLeft"> <!-- Buttons -->

            <a href = "javascript:startGame(1);" class = "animated shake">Single player</a> // the single player button
            <a href = "javascript:startGame(2);" class = "animated shake">Two players</a> // to 2 players button
      </div>
</body>
</html>

js:

var choise = 0; //global

function startGame(i){
    if (i == 1)
        choise = 1;     //change according to parameter
    else
        choise = 1;
}

有可能吗?

谢谢!

【问题讨论】:

    标签: javascript html function


    【解决方案1】:

    您不能传递用户为响应文档加载而选择的值。文档加载不是响应选择而发生的事情。 (除非在前一页上做出了选择,在这种情况下,您必须以某种方式将值传递给新文档 - 例如查询字符串或本地存储 - 然后从那里读回。)

    您要么等待按钮被点击,要么将值放入参数中。 (在问题的代码中,onload 属性中的i 未定义)。

    【讨论】:

    • 我希望页面根据按下的按钮进行更改.. 我该如何管理呢?
    • 如果“更改”是指“加载新页面”,则使用常规链接而不是 JavaScript。如果您的意思是“修改现有的 DOM”,那么您可以让您的 JavaScript 函数做一些更有趣的事情,即设置一个变量(理想情况下,了解addEventListener 和渐进式增强)。无论哪种方式,您都不要使用onload
    猜你喜欢
    • 2016-06-17
    • 1970-01-01
    • 2013-08-08
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2014-08-16
    相关资源
    最近更新 更多