簡體   English   中英

jQuery 選擇器輸入 [type=text]:nth-child(2) 不工作

[英]jQuery selector input[type=text]:nth-child(2) not working

我無法使用與輸入相關的 ID 或 class 名稱,因為它們是在輸入時隨機生成的。

渲染看起來像這樣:

<div class='dateSearch'>
  <label>Label 1</label>
  <input type='text' id='random_id_1'/>
  <span>Icon</span>
  <input type='text' id='random_id_2'/>
  <span>Icon</span>
  <input type='button' id='searchBtn'/>
</div>

我無法控制渲染,也無法更改任何內容。 所以相反,我試圖抓住第二個文本輸入並在它之前添加一個 label 。

<script>
  $('<label>Label 2</label>').insertBefore('.dateSearch input[type=text]:nth-child(2)')
</script>

.dateSearch input[type=text]將在兩個文本輸入前添加 label,但:nth-child(2)似乎不想工作。

我試過.dateSearch > input:nth-child(2)也沒有成功。 我只是想在第二個輸入元素之前添加一個 label 。

 $('<label>Label 2</label>').insertBefore('.dateSearch input[type=text]:nth-child(2)')
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <div class='dateSearch'> <label>Label 1</label> <input type='text' id='random_id_1'/> <span>Icon</span> <input type='text' id='random_id_2'/> <span>Icon</span> <button type="button" class="btn btn-secondary">Search</button> </div>

希望它看起來像這樣:

Label_1 [輸入文本](圖標Label_2 [輸入文本](圖標)[按鈕]

你熟悉eq()嗎? 這可以解決子選擇器問題,因為您也可以按類型定位元素。

如果可以的話,不要忘記在 label 上添加一個for屬性以方便訪問。

 const secondInput = $('.dateSearch input[type=text]').eq(1); // zero-based const secondInputId = secondInput.attr('id'); // optional, but wise const label = $('<label>Label 2</label>'); label.attr('for', secondInputId); // optional, but wise label.insertBefore(secondInput);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class='dateSearch'> <label>Label 1</label> <input type='text' id='random_id_1' /> <span>Icon</span> <input type='text' id='random_id_2' /> <span>Icon</span> <button type="button" class="btn btn-secondary">Search</button> </div>

暫無
暫無

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

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