String
オブジェクトの値を取得するには、String.toString()
を使用する必要があります。
セレクタの配列が必要な理由はわかりませんが、ここでは2つの解決策があります。
解決策を使用してString.toString()
;
// Array of strings to be used as element selectors.
var selectors = ['#element1', '#element2'];
// Using $.each()
$.each(selectors, function() {
// String.toString() returns the value of the String object.
var $this = $(this.toString());
$this.click(function() {
console.log('Clicked element(1) =', this.id || this); // DEBUG
});
});
String.join()
を使用した代替ソリューション。
// Using String.join()
$(selectors.join(',')).click(function(event) {
event.preventDefault(); // This is to not follow the link
// Notice that "this" now referes to the current/clicked element
// and not any string value from the "selectors" array.
console.log('Clicked element(2) =', this.id || this); // DEBUG
});
私demoを参照してください。
セレクタの配列が本当に必要ない場合は、このような単純なmultiple selectorをお勧めします。
$('#element1, #element2').click(function() { ... });
+1 'this'は' String'オブジェクトで、通常の文字列ではありませんが、答えに私。 – Davy8
+1。なぜかそれがうまくいかなかった理由を説明してもいいですが、 '.join()'のほうが良い方法です(別の理由で配列が必要であると仮定して)。 – nnnnnn