JQuery添加具有最接近标签名称的类

时间:2011-11-23 21:54:16

标签: javascript jquery

我有一张表需要一些自定义主题。它有很多文本输入,它们都需要自定义宽度。我认为根据每个字段的标签名称添加自定义CSS类会很不错。我是那里的一部分,但由于某种原因,我正在拿起表格中任何给定标签的所有标签名称,而不是我想要的最接近的标签名称。

这是我的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 .input-text类中,而不是最近的(最接近的)。我确信我做错了但不确定是什么。

我也想知道是否可以根据输入名称添加一个类

1 个答案:

答案 0 :(得分: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