简体   繁体   中英

JavaScript - CSS element style won't change?

I'm making a poker program. I have a grid of divs for where the cards go. The user can click to enter a card so that the image appears in the selected area. Each div has a default 1px dotted black border, and when the user clicks on one of them, the border changes style to a 2px solid blue border. In the function, the borders on all the divs are supposed to change back to the default, and then the border style changes for the one that was clicked. The problem is that if the user enters a card into one of the divs and then they click the div again while it's still selected, that div will stay selected forever. Here is the function:

 var clickCardLocation = function(e){ var target = e.target || e.srcElement; //target element of click var cardClass = document.getElementsByClassName("card"); //creates array of div class="card" elements var SELECTED = "2px solid blue"; var DESELECTED = "1px dotted black"; for (var i = 0; i < cardClass.length; i++){ //loop through all card divs in gui cardClass[i].style.border = DESELECTED; //deselect them } target.style.border = SELECTED; //change border for only clicked div }; 

When I debugged it, it seems logically sound, but it's not acting right. The border stays selected on the screen, even though the debugger says that cardClass[i].style.border = "1px dotted black".

There is no getElementByClassName . There is getElementsByClassName . I am not sure how the debugger would get there.

I know it has been almost two years since this question was asked, but I thought I'd answer it...maybe it will help someone.

A jQuery approach:

$(document).ready(function() { //wait until the document is ready
  $('div.card').click(function() { //listen for click on divs with class 'card'
   $('div.card').each(function() { //for each div with class 'card'
    $(this).removeClass('selected'); //take off the 'selected' class that may be on there from other clicks
   });

   $(this).addClass('selected'); //apply the selected class to only the div that was clicked
  });
 });

Where the 'selected' class has border: 2px solid blue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM