2016-11-18 110 views
1

當頁面使用onload時,我必須設置價格。使用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來完成。任何幫助,將不勝感激。

+3

試'的window.onload =函數(){}' – miglio

回答

1

事情是這樣的:

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

這是寫在純JavaScript沒有的jQuery

$(document).ready(function() { 
    // Do stuff... 
}); 

模擬。還有一個選擇是使用

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

感謝@mplungjan對於這個想法。

+1

的window.onload =函數(){}爲評論是更大的analoque和更相容 – mplungjan

2

如果您正在尋找設定重點,這是你可以做的。

另外,值得一讀這post什麼是不同的負載事件和意義。

希望這會有所幫助。

document.addEventListener("DOMContentLoaded",() => { 
 
    document.querySelector("#price").focus(); 
 
});
<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>