改变下一个('输入')的attr失败

时间:2012-08-16 10:42:28

标签: jquery input attr next

我正在尝试将dom中的下一个输入设置为只读但出错了。

继承人jQuery:

$('select.expense-code').change(function(e) {

    // If expense code is travel mileage
    if ($(this).val() == '5') {
        // Set miles to read only
        var currentRowAmount = $(e.target).next("input.amount");
        currentRowAmount.attr('readonly', true);
    }

});

这是dom的一部分:

DOM

我尝试过设置bg颜色等,但没有任何效果,我确定它位于.next()位,但需要朝正确的方向发射。 Console.log()只给你[]。

提前致谢

2 个答案:

答案 0 :(得分:2)

.next()抓住下一个兄弟,它不搜索任何东西,过滤器参数只是为了确保下一个兄弟是在过滤器内。

来自docs

  

描述:获取每个元素的紧随其后的兄弟   匹配元素的集合。如果提供了选择器,则检索   只有当它与那个选择器匹配时才是下一个兄弟。

由于你已经在目标上拥有了id,你可以这样做:

// current id ($(this).prop('id')) is Expense0ExpenseCode
var curId = $(this).prop('id');

// you are targetting Expense0Amount, which has the same Expense0 as the prefix
// so replace the suffix (ExpenseCode -> Amount):
var targetId = curId.replace('ExpenseCode', 'Amount');

// do the prop change
$('#' + targetId).prop('readonly', true);

一个班轮:

$('#' + $(this).prop('id').replace('ExpenseCode', 'Amount')).prop('readonly', true);

答案 1 :(得分:0)

您的元素根本不是兄弟姐妹,它们位于两个不同的父.span1元素中:

$('select.expense-code').on('change', function(e) {
    if ($(this).val() == '5') {
        $(this).closest('.span1')
               .next('.span1')
               .find('input.amount')
               .prop('readonly', true);
    }
});
相关问题