简体   繁体   中英

How do I change the color of a div with onclick by calling a function in JavaScript?

If I put this.style.background="#000"; inline in the div, like onclick="this.style.background="#000"; , it works. However, if I put that in a function and call the function from the same onclick event, it doesn't work. However, if I make the function do something else (like bring up an alert box), it does work. What's going on?

Here's the code:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<style>
.tile {
    width: 48px;
    height: 48px;
    margin: 0px;
    padding: 0px;
    float: left;
    background-color:red;
    border: 1px solid black;
}
</style>
</head>

<body>
<div class="tile" onclick="myFunction()"></div>

<script>
function myFunction() {
    this.style.background="#000000";
}
</script>

</body>

</html>

I noticed you're including jQuery. You should strongly consider separating your markup and JavaScript . If you do go that route, here's what that would look like:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<style>
.tile {
    width: 48px;
    height: 48px;
    margin: 0px;
    padding: 0px;
    float: left;
    background-color:red;
    border: 1px solid black;
}
</style>
</head>

<body>
<div class="tile"></div>

<script>
$(function () {
    $(".tile").click(function () {
        $(this).css('background-color', '#000000');
    });
});
</script>

</body>

</html>

Example: http://jsfiddle.net/6zAN7/9/

If you would like to do it this way you need to pass the reference of DIV element when you invoke your function. During execution of your onclick handler "this" will reference to the current element. Pass it as an argument!

Here is the corrected code:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<style>
.tile {
width: 48px;
height: 48px;
margin: 0px;
padding: 0px;
float: left;
background-color:red;
border: 1px solid black;
}
</style>
</head>

<body>
<div class="tile" onclick="myFunction(this)"></div>

<script>
function myFunction(divObj) {
    divObj.style.background="#000000";
}
</script>

</body>

</html> 
<div class="tile" onclick="myFunction(this)"></div>

<script>
function myFunction(x) {
    x.style.background="#000000";
}
</script>

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