Reputation: 1360
this is my code:
$(document).ready(function() {
for( var i = 0 ; i < 8 ; i++ ){
for( var j = 0 ; j < 8 ; j++ ){
var $class = getPieceName(board[i][j][0])
$(.$class ????).click(function() {
$(this).css('background-color', 'red');
});
}
}
});
As you can see, I want to change the background color of an element. The for-loops are needed to get the element, in an array, which the user clicked on. How to write the variable ($class) as a class?
Upvotes: 1
Views: 619
Reputation: 862
It might be simpler to apply a class or data-attribute to all your board pieces, like class="board_piece" data-board-x="1" data-board-y="2"
and then bind the click handler to a selector for that:
$('.board_piece').click(function() { $(this).css(...) }
You could use the data-board-x and -y coordinates I added to retrieve the actual position within the board inside your click handler.
Upvotes: 0
Reputation: 2526
If class is a string you can use it like this:
$("." + $class).click(function(){ ... });
Upvotes: 2
Reputation: 6332
you can name your variable then concat it into your selector since its a string not a JQ object.
var class = getPieceName(board[i][j][0])
$('.' + class).click(function() {
Upvotes: 2