简体   繁体   English

点击事件时更改div背景颜色

[英]Change div background color on click event

I am trying to change div color on click but it is not working: 我正在尝试更改div的点击颜色,但它不起作用:

<html>
    <head>
        <script>
            function data(){
                var MyDiv1 = document.getElementById('newdata').innerHTML;
                alert(MyDiv1)   
                if(MyDiv1==1) {
                    document.getElementsById('newdata').style.backgroundColor = "green";
                }
            }
        </script>
    </head>
    <body >
        <div id="newdata" style="background-color: red; width: 100px;height: 50px;">
            1
        </div>
        <a href="#" onclick="data();">Logout</a>
    </body>
</html>

Where am I wrong here? 我在哪里错了?

Any help will be appreciated 任何帮助将不胜感激

<html>
    <head>
    </head>
    <body >
        <div id="newdata" style="background-color: red; width: 100px;height: 50px;">
            1
        </div>
        <a href="#" onclick="data();">Logout</a>
    </body>
</html>
  <script>
       function data(){

       document.getElementById('newdata').style.backgroundColor = "green";

       }
  </script>

http://jsfiddle.net/n2uk4br1/ http://jsfiddle.net/n2uk4br1/

1) Script at the end; 1)脚本结尾;

2) Element not Elements 2)元素而不是元素

3) Call the right div name 3)调用正确的div名称

4) That alert and if don't have a purpose 4)该警报,如果没有目的

it should be newdata 它应该是newdata

 document.getElementById('newdata').style.backgroundColor = "green";

so your function will be 所以你的功能是

function data(){
                var MyDiv1 = document.getElementById('newdata').innerHTML;
                alert(MyDiv1)   
                if(MyDiv1==1) {
                    document.getElementById('newdata').style.backgroundColor = "green";
                }
            }

There were a couple of problems with your attempt. 您的尝试有两个问题。 The following snippet does what you want: 以下代码片段可以满足您的需求:

 function data(){ var myDiv = document.getElementById('newdata'); var content = myDiv.innerHTML; if (content.trim() === "1") { myDiv.style.backgroundColor = "green"; } } 
 <div id="newdata" style="background-color: red; width: 100px;height: 50px;"> 1 </div> <a href="#" onclick="data();">Logout</a> 
Firstly, you must be careful to distinguish between your <div> element and its contents. 首先,您必须小心区分<div>元素及其内容。 I have put the two into separate variables. 我已将两者放入单独的变量中。 I have used .trim() to remove any leading and trailing spaces from the contents of the <div> and also used the strict comparison === . 我已经使用.trim()<div>的内容中删除了任何前导和尾随空格,还使用了严格的比较===

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

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