2010-08-02 32 views
0

我希望有人可以幫我用jQuery選擇器的語法。我無法讓它工作! 我試圖選擇與包含類跨度div的表格行相關的輸入字段。這裏的HTML:如何使用jQuery選擇相鄰行的輸入子項?

<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> 

如果有一個與它有一類「form_error」的,有描述錯誤文本或者領域的DIV將創建(回聲form_error)錯誤。

我想在出現錯誤時選擇文本輸入,以便通過更改CSS來突出顯示,例如,將邊框的顏色改爲紅色。

這是jQuery的我試過了,但不工作:

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

有什麼建議?

回答

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:輸入」一間選擇 - TD元素永遠不會形成元素,很明顯你正在尋找一個輸入反正td元素的孩子

但是,這隻會暴露第二個錯誤:你不是在尋找該行的直接孩子,你正在尋找一個孫輩 - yet children() will search only the immediate descendants的上下文元素。你真的使用的是find() ...

$("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 

請注意,你的目的,你並不真的需要使用the :input selector - 在你給的例子input將工作也很不錯,因爲,它實際上是一個你正在尋找的<input>元素......但是如果你打算使用其他表單控件,輸入將會給你稍微更多的靈活性。

+1

非常感謝。特別感謝您解釋我做錯了什麼以及您的解決方案爲何工作。這是我學習的唯一方法! – musoNic80 2010-08-02 19:42:24

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