我无法使用与输入相关的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 Text>(Icon
您熟悉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>