2016-12-10 10 views
1

jQueryで$ .each関数を使用して、クリック時にさまざまな要素のクラスとIDを割り当てたり変更したりしています。私は、3つの別々の機能を持つのではなく、1つの機能にこれらを組み合わせる方法があるのだろうかと思っていました。

var stored = $.each; 

var myFunction = function() { 
    $(this).removeAttr("id"); 
}; 

    function numbers() { 

    //function 1 
    stored($(".numbers"), function(index, value) { 
     var num = index + 1 + "."; 
     $(value).empty(); 
     $(value).append(num); 
    }); 

    //function 2 
    stored($(".weight-change"), function(index) { 
     myFunction(); 
     $(this).attr("id", "weight" + index); 
    }); 

    //function 3 
    stored($(".onebox"), function(index) { 
     myFunction(); 
     $(this).attr("id", "shipprice1box" + index); 
    }); 
} 
+4

さまざまな要素に異なることがあります...それらを組み合わせることが合理的であるかどうかは分かりません。 – JCOC611

+1

あなたはそれを一般的にすることもできますし、idを削除するのも意味がなく、あなたはそれを置き換えます... – epascarello

+1

私は最初のコメントに同意します。 fn2とfn3を除いて、それらをすべて1つの方法に組み合わせるのは実際には意味がありません。 3つの簡潔なコードを持つ代わりに、さまざまなロジックフローを処理するために不要な条件付きのコードを1つにすることになります。ロジックの強制的な組み合わせにより、可読性が低下することがあります。これは、保守性を向上させる上で重要です – Taplar

答えて

1

ジェネリック関数を作成して呼び出すことができます。更新する前に属性を削除する必要はありません。処理時間を無駄にするだけです。 attrは機能をサポートしているため、それぞれの機能は必要ありません。

function updateIds (selector, prefix) { 
    $(selector).attr("id", function (index) { return prefix + index; }); 
} 

updateIds(".weight-change", "weight"); 
updateIds(".onebox", "shipprice1box"); 
1

コードの重複を避けるには(必要に応じてさらに編集できます)

var arr = ['.numbers', '.weight-change', '.onebox']; 

stored($(arr.join()), function(index, value) { 
    if ($(this).is(arr[0])) { 
     var num = index + 1 + "."; 
     $(value).empty(); 
     $(value).append(num); 
    } 
    else if ($(this).is(arr[1]) || $(this).is(arr[2])) { 
     myFunction(); 
     if ($(this).is(arr[1])) { 
      $(this).attr("id", "weight" + index); 
     } 
     else if ($(this).is(arr[2])) { 
      $(this).attr("id", "shipprice1box" + index); 
     } 
    } 
}); 
関連する問題