basically I have a table grid like the one below, just a lot bigger.
<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
And iv used CSS to make then all squares which are 60px by 60px, they wont contain any data but I want to be able to click on the individual squares so that the background color changes and if I click again it goes back to the origional background color. But I want to be able to highlight as many squares as I want. I know it would be in JavaScript, but how would I do this?
try this:
<table>
<tr>
<td>test 1</td>
<td>test 2</td>
</tr>
<tr>
<td>test 3</td>
<td>test 4</td>
</tr>
</table>
and script
window.onload = function(){
var all = document.getElementsByTagName("td");
for (var i=0;i<all.length;i++) {
all[i].onclick = inputClickHandler;
}
};
function inputClickHandler(e){
e = e||window.event;
var tdElm = e.target||e.srcElement;
if(tdElm.style.backgroundColor == 'rgb(255, 0, 0)'){
tdElm.style.backgroundColor = '#fff';
} else {
tdElm.style.backgroundColor = '#f00';
}
}
Well I'll post code in jQuery because I never liked how standard JS goes with selecting elements.. ;)
$("td").click(function() {
if($(this).css('background-color') == 'red') { $(this).css('background-color', 'green'); }
else { $(this).css('background-color', 'red'); }
});
In jQuery:
$('td').click(function() {
$(this).toggleClass('active');
});
See: http://jsfiddle.net/CpGVK/
I like Mihai Lorga's answer as it uses pure JavaScript. However jQuery is a lot easier to develop.
$("td").click(function(){
$(this).toggleClass("active");
});
something like this
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.