如何使用jQuery选择相邻行的输入子项?

时间:2010-08-02 19:17:12

标签: jquery jquery-selectors

我希望有人可以帮助我使用jQuery选择器的语法。我只是无法让它工作! 我正在尝试选择与包含具有类span的div的表行相关的输入字段。这是HTML:

<tbody>
  <tr><th scope="col"><label for="username">Username</label><br /><?php echo form_error('username');?></th></tr>
  <tr><td><input type="text" id="username" name="username" value="<?php echo set_value('username');?>"/></td></tr>
  <tr><th scope="col"><label for="password">Password</label><br /><?php echo form_error('password');?></th></tr>
  <tr><td><input type="password" id="password" name="password" /></td></tr>
</tbody>

如果任何一个字段都有错误,将创建一个div(echo form_error),它有一个“form_error”类,并且有描述错误的文本。

如果出现错误,我想选择文本输入,以便我可以通过更改CSS来突出显示,例如将边框的颜色更改为红色。

这是我尝试的jQuery但是没有用:

$(document).ready(function() {
$("tr:has(.form_error)").next().children("td:input").css("border-color", "#C21312");
});

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您有两个主要错误。请允许我打破您的代码:

$("tr:has(.form_error)") // finds row containing element with form_error class
  .next() // move to the next row
  .children("td:input") // find a direct child of the row 
                        // that is both a td and input element
  .css("border-color", "#C21312"); // make border color red

正如Sarfraz指出的那样,你需要在“td:input”选择器中有一个空格 - td元素永远不会形成元素,显然你正在寻找td元素的输入 child

但这只暴露了第二个错误:你不是在寻找行的直接子项,而是在寻找孙子 - {3}}的上下文元素。您 想要使用的是yet children() will search only the immediate descendants ...

$("tr:has(.form_error)") // finds row containing element with form_error class
  .next() // move to the next row
  .find("td :input") // find an input element descendant of the row 
                     // that has a td as its parent
  .css("border-color", "#C21312"); // make border color red

请注意,出于您的目的,您实际上不需要使用find() - input也可以正常工作,因为在您给出的示例中,它实际上是<input>你正在寻找的元素......但是如果你打算使用其他表单控件,那么:输入会给你更多的灵活性。

答案 1 :(得分:0)

$(document).ready(function() {
    $("tr:has(.form_error)").parent('tr').find("input").css("border-color", "#C21312");
});