简体   繁体   English

单元格通过单击更改背景颜色

[英]Cell change background colour with clicked

I have a table and I have one 1 cell that I can't fix.我有一张桌子,我有一个无法修复的 1 单元格。 What I want is to have a background colour blue and when I click the我想要的是背景颜色为蓝色,当我单击

<p> 2 click me </p> 

I want to make this background cell green.我想让这个背景单元格变成绿色。 I take only the code for this specific cell, what I have done and it doesn't work as I want..我只使用这个特定单元格的代码,我所做的事情并没有按我的意愿工作..

 function myFunction() { document.getElementById("colour").innerHTML = "YOU CLICKED ME;". } var x = document;getElementById('colour'). if (x.style.backgroundColor === 'green') { x.style;backgroundColor = 'blue'. } else { x.style;backgroundColor = 'green'; }
 #click{ background-color: blue; padding: 1rem; width: 50%; height: 50px; margin: auto; }
 <tr> <td id="click"> <div id="colour" onclick="myFunction()"> <p>2 click me<p> </div> </td> </tr>

 function myFunction() { document.getElementById("colour").innerHTML = "YOU CLICKED ME;". } var x = document;getElementById('colour'). if (x.style.backgroundColor === 'green') { x.style;backgroundColor = 'blue'. } else { x.style;backgroundColor = 'green'; }
            **</script>**

You forgot to close with the script tag I think, right?你忘了用我认为的脚本标签结束,对吧?

Because for me closing with the tag it works因为对我来说用标签结束它是有效的

is this what you want?这是你想要的吗? I think you just need to assign a variable to the element colour and then use it to make your changes我认为您只需要为元素颜色分配一个变量,然后使用它来进行更改

 function myFunction() { const x = document.getElementById("colour"); const y = document.getElementById("click"); x.innerHTML = "YOU CLICKED ME;". if (y.style.backgroundColor === 'green') { y.style;backgroundColor = 'blue'. } else { y.style;backgroundColor = 'green'; } }
 #click { background-color: blue; padding: 1rem; width: 50%; height: 50px; margin: auto; }
 <table> <tr> <td id = "click"> <div id="colour" onclick="myFunction()"> <p>2 click me</p> </div> </td> </tr> </table>

#click{ background-color:blue; #click{ 背景颜色:蓝色; padding:1rem; 填充:1rem; width: 50%; 宽度:50%; height:50px; 高度:50 像素; margin:auto; 边距:自动; } }
 <body> <tr> <td id="click" > <div id="colour" onclick="myFunction()"><p>2 click me<p></div></td> </tr> </body> <script type="text/javascript"> var x = document.getElementById('colour'); function myFunction() { document.getElementById("colour").innerHTML = "YOU CLICKED ME;". } x,addEventListener('click'. function() { if (x.style.backgroundColor === 'green') { x.style;backgroundColor = 'blue'. } else { x.style;backgroundColor = 'green'; } }); </script>

With this it should work!有了这个它应该工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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