1

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?

4 Answers 4

2

If class is a string you can use it like this:

$("." + $class).click(function(){ ... });
Sign up to request clarification or add additional context in comments.

Comments

2

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() {

Comments

1

It think all you need is '.' + $class

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.