0

嗨,我正在使用掩码插件,我需要向输入级别元素添加一个类,但是我似乎无法正确定位它,而.next()只是进入下一个级别<td>

这是我正在处理的一个Jfiddle,如您所见,我需要将phone_us部分动态添加到类属性中,因为我屏蔽了它<input type="text" class="" name="" value="">

Javascript

$(document).ready(function(){

$('td').each(function (index) {
   var divHTML =  $(this).text();  

if(divHTML.indexOf("Phone") >= 0)
     {
    $(this).next().css('background-color', 'blue');       
    $(this).next().closest('input').addClass('phone_us');
    $('.phone_us').mask('(999) 999-9999');
     }
});
});

HTML

<td class="label">Phone #</td>
<td class="field"><input type="text" class="label_box" name="" value=""></td>
4

1 回答 1

3

.closest()选择所选元素的最匹配的父/祖父...:

对于集合中的每个元素,通过测试元素本身并向上遍历其在 DOM 树中的祖先来获取与选择器匹配的第一个元素。

改用findorchildren方法:

$('td:contains("Phone")').next()
                         .css('background-color', 'blue')       
                         .find('input')
                         .addClass('phone_us')
                         .mask('(999) 999-9999');

http://jsfiddle.net/dyNZg/

于 2013-06-02T05:26:59.343 回答