由于它們是如何在輸入上隨機生成的,我無法使用與輸入關聯的 ID 或類名。
渲染看起來像這樣:
<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>
我無法控制渲染,也無法更改任何內容。所以相反,我試圖獲取第二個文本輸入并在它之前添加一個標簽。
<script>
$('<label>Label 2</label>').insertBefore('.dateSearch input[type=text]:nth-child(2)')
</script>
.dateSearch input[type=text]將在兩個文本輸入的前面添加標簽,但:nth-child(2)似乎不想作業。
我已經嘗試過 .dateSearch > input:nth-child(2),但也未能奏效。我只想在第二個輸入元素之前添加一個標簽。
$('<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/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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 [輸入文本](圖示)[按鈕]
uj5u.com熱心網友回復:
你熟悉eq()嗎?這可以讓您解決子選擇器問題,因為您也可以按型別定位元素。
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377887.html
