2016-11-18 7 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); 

これは、jQueryのない純粋なJavaScriptで書かれた

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

の類似体です。もう1つの選択肢は、このアイデアに@mplungjanに感謝します。

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

ありがとうございます。

+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>

関連する問題