【发布时间】:2022-01-14 12:31:32
【问题描述】:
我无法使用与输入关联的 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/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 [ 输入文本 ](图标)[按钮]
【问题讨论】:
-
如果您将其设为
input:nth-child(2)[type=text]或$(".dateSearch").find(":nth-child(2)").filter("input[type=text]"),您的选择器是否有意义?无论您应用什么其他过滤器,:nth-child始终是第 n 个孩子 -
您的
random_id_2不是:nth-child(4)(2) -
是的,这使得使用
:nth-child()本身就很笨拙并且可能很脆弱。最好按元素类型和索引定位,如果不是更可靠的话。
标签: javascript html jquery jquery-selectors bootstrap-5