簡體   English   中英

JavaScript:查找表單輸入的第一個子項是輸入框還是選擇下拉列表

[英]JavaScript: Finding whether first child of a form input is an input box or select dropdown

我正在嘗試在HTML格式內搜索DD標記的表單上編寫腳本。 當找到標簽時我想檢測DD標簽中包含的第一個子項是輸入框還是選擇框,以及是否將焦點設置為它。 在一個頁面上可能有多個DD標記,所以我只關心它的第一個實例。

本質上,我想要做的是當頁面加載時,它關注頁面上的第一個表單字段,以便用戶可以直接輸入數據而無需單擊框或下拉列表。 我需要他的邏輯用純JS編寫(所以請不要使用JQuery解決方案)並且如果給定頁面可能有一個輸入框作為第一個字段或選擇框作為第一個字段。

JSFiddle: http//jsfiddle.net/3UqSq/

任何幫助都會很棒!

輸入框的HTML:

  <div class="container">
     <form class="myform">
       <fieldset>
          <dl>
            <dt><label for="input1">Label 1</label></dt>
            <dd>
               <input id="input1" type="text" value=""/>
               <div>This is some extra DIV's for copy</div>
               <div>This is some extra DIV's for copy</div>
               <div>This is some extra DIV's for copy</div>
            </dd>
            <dt><label for="input2">Label 2</label></dt>
            <dd>
               <input id="input2" type="text" value=""/>
               <div>This is some extra DIV's for copy</div>
               <div>This is some extra DIV's for copy</div>
               <div>This is some extra DIV's for copy</div>
            </dd>
         </dl>
       </fieldset>
     </form>
   </div>

選擇框的HTML:

  <div class="container">
     <form class="myform">
       <fieldset>
          <dl>
            <dt><label for="input1">Label 1</label></dt>
            <dd>
               <select id="input1">
                 <option>Option 1</option>
                 <option>Option 2</option>
                 <option>Option 3</option>
               </select>
               <div>This is some extra DIV's for copy</div>
               <div>This is some extra DIV's for copy</div>
               <div>This is some extra DIV's for copy</div>
            </dd>
            <dt><label for="input2">Label 2</label></dt>
            <dd>
               <input id="input2" type="text" value=""/>
               <div>This is some extra DIV's for copy</div>
               <div>This is some extra DIV's for copy</div>
               <div>This is some extra DIV's for copy</div>
            </dd>
         </dl>
       </fieldset>
     </form>
   </div>

將其包含在頁面底部的腳本中或加載后:

​var dd = document.getElementsByTagName('dd')[0];

if (dd.children[0].tagName.toLowerCase() == 'select' ||
    dd.children[0].tagName.toLowerCase() == 'input') {
    dd.children[0].focus();
}

見演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM