JQuery: 属性値の検索と置換

属性値の検索と置換がうまくいきません。

このhtmlを考えてみます。

<tr id="rules[0]">
    <td>
        <input id="rules0.isActive1" name="rules[0].isActive" type="checkbox" value="true"/><input type="hidden" name="_rules[0].isActive" value="on"/>
    </td>
    <td>
        <select id="rules0.leftCondition.name" name="rules[0].leftCondition.name">
            ...
        </select>
    </td>

各 's の name 属性を適切な数で更新したいのです。例えば rules[0].isActive は rules[10].isActive に更新されます。

私はこのJQueryのスニペットを使用しています。

$(newRow).find('[id*="rules"]').each(function(){
    // Update the 'rules[0]' part of the name attribute to contain the latest count 
    this.name.replace('rules\[0\]','rules\[$count\]');
}); 

ここで、newRow は全体の ブロックを保持する変数で、count は最新のカウンタ値を保持します。 しかし、このコードをデバッグすると、"this.name" が未定義であるように思われます。

私はどこで間違っているのでしょうか?

ありがとうございます。

ソリューション

要素の属性を更新するには、.attr関数を使用する必要があります。また、jQueryのコンテキストでこれを使用する場合は、$(this)構文を使用する必要があります。もし私があなたの意図を理解するならば、それはそのようなものであるべきです。

$(newRow).find('[id*="rules"]').each(function(){
    // Update the 'rules[0]' part of the name attribute to contain the latest count 
    $(this).attr('name',$(this).attr('name').replace('rules\[0\]','rules\[$count\]'));
}); 
解説 (0)

$(this).attr('name')の代わりにthis.name` を使用する必要があります。

解説 (0)

これを試してみてください。

$(this).attr('name', $(this).attr('name').replace('rules\[0\]','rules\[$count\]'));
解説 (0)