Javascript 使用onload将输入设置为焦点
当页面使用onload时,我必须设置价格以集中精力Javascript 使用onload将输入设置为焦点,javascript,html,Javascript,Html,当页面使用onload时,我必须设置价格以集中精力 <body style="border: solid 1px black; margin-left: auto;margin-right: auto;width: 500px;"> <form> <fieldset style="margin:25px";><legend>Discount Calculator</legend> <
<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>
折扣计算器
输入价格:
函数事物()
{
文件:focus()
}
我知道我做错了什么。我可以通过使用document.findElementById(“price”).focus()
轻松地将其设置为焦点,但对于此任务,我需要作为onload来完成。如有任何帮助,我们将不胜感激。诸如此类:
document.addEventListener( 'DOMContentLoaded', function () {
// Do stuff...
}, false );
它类似于
$( document ).ready(function() {
// Do stuff...
});
使用纯Javascript编写,不使用jQuery。还有一个选择是使用
window.onload = function() {
// Do stuff...
}
感谢@mplungjan的这一想法。如果您希望设置焦点,以下是您可以做的 此外,关于不同的加载事件和含义,可能值得一读 希望这有帮助
document.addEventListener(“DOMContentLoaded”,()=>{
document.querySelector(“#price”).focus();
});代码>
折扣计算器
输入价格:
trywindow.onload=function(){}
window.onload=function(){}如注释所示,更具分析性和兼容性