使用onload将输入设置为焦点

时间:2016-11-18 20:59:27

标签: javascript html5

我必须在使用onload的页面设置价格。

<body style="border: solid 1px black; margin-left: auto;margin-right: auto;width: 500px;">
    <form>
        <fieldset style="margin:25px";><legend>Discount Calculator</legend>
            <div style="text-align: right; margin-right: 25%;">
            <label>Enter Price: <input onload = "thing()" type="text" name="price" id="price"></label><br><br>
            </div>
        </fieldset>
    </form>


    <script type="text/javascript">
        function thing()
        {
            document.focus()
        }

    </script>
</body>

我知道我做错了什么。我可以使用document.findElementById("price").focus()轻松地将其设置为焦点,但对于此赋值,我需要将其作为onload进行。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

如果你正在寻找焦点,那么你可以做到这一点。

此外,对于不同的加载事件和含义,可能值得阅读此post

希望这有帮助。

&#13;
&#13;
document.addEventListener("DOMContentLoaded", () => {
  document.querySelector("#price").focus();
});
&#13;
<form>

  <input type="text" name="dummy-1">
  <input type="text" name="dummy-2">
  <fieldset style="margin:25px" ;>
    <legend>Discount Calculator</legend>
    <div style="text-align: right; margin-right: 25%;">
      <label>Enter Price:
        <input onload="thing()" type="text" name="price" id="price">
      </label>
      <br>
      <br>
    </div>
  </fieldset>
  <input type="text" name="dummy-1">
  <input type="text" name="dummy-2">
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这样的事情:

document.addEventListener( 'DOMContentLoaded', function () {
    // Do stuff...
}, false );

这是

的类似物
$( document ).ready(function() {
    // Do stuff...
});

用纯Javascript编写,不带jQuery。还有一个选择是使用

window.onload = function() {
  // Do stuff...
} 

感谢@mplungjan这个想法。