2011-11-23 91 views
0

我有一個表,需要一些自定義主題。它有很多文本輸入,它們都需要自定義寬度。我想根據每個字段的標籤名稱簡單地添加自定義CSS類是很好的。我是那裏的一部分,但由於某種原因,我爲表格中的任何給定標籤拾取所有標籤名稱,而不是我所希望的最接近的標籤名稱。JQuery添加類與最接近的標籤的名稱

這裏是我的JQuery:

$('td.label-text', this).each(function() { 
// add class with name of the label text 
$('td.input-text').addClass($(this).text().replace(/[^a-z]/gi,'').toLowerCase() + ' ').closest("td.label-text"); 
}); 

下面是一些示例HTML輸出:

<tr> 
<td class="label-text">Rule Name*:</td> 
<td class="input-text effectivedate rulename employeeid createrulefor ipaddress active searchby"> 
<input type="text" name="ruleName" value=""> 
</td> 
</tr>  

<tr> 
<td class="label-text">Employee ID:</td> 
<td class="input-text effectivedate rulename employeeid createrulefor ipaddress active searchby"> 
<input type="text" name="employeeId" value="" id="empnotext"> 
</td> 
</tr> 

正如你所看到的所有的標籤名都被添加到每個TD。輸入文本類,而不是最近的(最近的)一個。我確信我做錯了什麼,但不知道是什麼。

我也想知道如果一個類可以根據輸入名字

+0

你是什麼意思「我也想知道如果一個類可以根據輸入名字被添加」呢? – JesseBuesking

回答

2

你必須使用this在循環中被加入。目前,您正在選擇所有具有選擇器td.input-text(每次迭代)的元素。小提琴:http://jsfiddle.net/WCTyz/2/

$('td.input-text input', this).each(function() { 
    // add class with name of the label text 
    var $this = $(this); 
    var addclass = $this.parents("tr:first").children("td:first") 
          .text().replace(/[^a-z]/gi,'').toLowerCase(); 
    $this.addclass(addClass); 
}); 

此外,addClass方法自動分隔空間的交易。您不必手動用空格後綴名稱。

選擇的說明:

td.input-text input  For each <td class="input-text"> ???? <input> ??? </td> : 

Get class name: 
.parents("tr:first") Select the current row 
.children("td:first") Select the first cell 
.text()     Get the textual value 
+0

這是唯一的作品,但它將類添加到.label-text類(第一個td)而不是.input-text td。但是我越想到它,我的邏輯可能有缺陷,因爲有時每個標籤有多個輸入。所以也許在基於輸入名稱=「somename」的同一個td中添加一個類?謝謝。 –

+0

其實我的意思是添加一個類到輸入的權利,所以如果它是'input name =「somename」',添加一個基於它的類,所以它'輸入名稱=「somename」class =「somename」' –

+0

感謝羅布,但它似乎沒有添加一個類到輸入字段。我想也許你的選擇是不對的'tr:第一個'?我嘗試過'td:first',但那也行不通。 –