【问题标题】:jQuery selector input[type=text]:nth-child(2) not workingjQuery 选择器输入 [type=text]:nth-child(2) 不工作
【发布时间】: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 &gt; input:nth-child(2),但也没有用。我只是想在第二个输入元素之前添加一个标签。

  $('&lt;label&gt;Label 2&lt;/label&gt;').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


【解决方案1】:

你熟悉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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    相关资源
    最近更新 更多