2017-07-13 11 views
1

jQueryを1ずつ増やしたいとします。私は1によってそのIDを増やしたいの例同じコールバックをjQueryの異なるattrに渡しますか?

<label for='question_1' class='question_content_label'> 
<input type='text' id='question_1' class='question_content'> 

については

ので、私はこのようにjQueryで行うだろうと思った

<label for='question_2'> 
<input type='text' id='question_2'> 

次のようになります。

$('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); 
      }); 
     }); 

Iドンこれを繰り返す必要はありません:

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_label').attr('for','increment_attr_number'); 

それは

感謝:)

答えて

4

あなたが渡す必要が動作しません。関数リファレンスであり、文字列表現ではありません。

$('body').find('.question_content_label') 
     .attr('for', increment_attr_number); 
+0

thx。私はそれについて考えなかったPHPのためにあるかもしれない:) – user80946

関連する問題