如何通过在 JavaScript 中调用函数来使用 onclick 更改 div 的颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14924543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change the color of a div with onclick by calling a function in JavaScript?
提问by FlyingLizard
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?
如果我将this.style.background="#000";内联放在 div 中,例如onclick="this.style.background="#000";,它会起作用。但是,如果我把它放在一个函数中并从同一个 onclick 事件调用该函数,它就不起作用。但是,如果我让该函数执行其他操作(例如弹出警告框),它确实可以工作。这是怎么回事?
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>
回答by Andrew Whitaker
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:
我注意到你包括 jQuery。您应该强烈考虑将您的标记和 JavaScript 分开。如果你真的走那条路,这就是它的样子:
<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/
回答by Attila Wind
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!
如果您想这样做,您需要在调用函数时传递 DIV 元素的引用。在您的 onclick 处理程序执行期间,“this”将引用当前元素。将其作为参数传递!
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>
回答by A. Rodas
<div class="tile" onclick="myFunction(this)"></div>
<script>
function myFunction(x) {
x.style.background="#000000";
}
</script>

