Javascript 在jQuery中将相同的回调传递给不同的attr?
假设我想将jQuery的任意属性数增加1 比如说Javascript 在jQuery中将相同的回调传递给不同的attr?,javascript,jquery,Javascript,Jquery,假设我想将jQuery的任意属性数增加1 比如说 <label for='question_1' class='question_content_label'> <input type='text' id='question_1' class='question_content'> 我不想重复这一点: function (index,name){ return name.replace(/(\d+)/, function(fullMatch,n)
<label for='question_1' class='question_content_label'>
<input type='text' id='question_1' class='question_content'>
我不想重复这一点:
function (index,name){
return name.replace(/(\d+)/, function(fullMatch,n){
return Number(n) + 1;
console.log(n);
});
};
我想创建这样的函数
function increment_attr_number(index,name){
return name.replace(/(\d+)/, function(fullMatch,n){
return Number(n) + 1;
console.log(n);
});
};
然后像这样经过:
$('body').find('.question_content').attr('for',function (index,name){
return name.replace(/(\d+)/, function(fullMatch,n){
return Number(n) + 1;
console.log(n);
});
});
$('body').find('.question_content_label').attr('for',function (index,name){
return name.replace(/(\d+)/, function(fullMatch,n){
return Number(n) + 1;
console.log(n);
});
});
$('body').find('.question_content_label').attr('for','increment_attr_number');
但它不起作用
谢谢:您需要传递函数引用,而不是它的字符串表示形式
$('body').find('.question_content_label')
.attr('for', increment_attr_number);
您需要传递函数引用,而不是它的字符串表示形式
$('body').find('.question_content_label')
.attr('for', increment_attr_number);