如何通过调用JavaScript中的函数来使用onclick更改div的颜色?
如果我把如何通过调用JavaScript中的函数来使用onclick更改div的颜色?,javascript,Javascript,如果我把这个.style.background=“#000”在div中内联,比如onclick=“this.style.background=“#000”,它可以工作。但是,如果我把它放在一个函数中,并从同一个onclick事件调用该函数,它就不能工作。但是,如果我让该函数做其他事情(比如打开一个警报框),它可以工作。发生了什么 代码如下: <!DOCTYPE html> <html> <head> <script type="text/javascri
这个.style.background=“#000”代码>在div中内联,比如onclick=“this.style.background=“#000”
,它可以工作。但是,如果我把它放在一个函数中,并从同一个onclick事件调用该函数,它就不能工作。但是,如果我让该函数做其他事情(比如打开一个警报框),它可以工作。发生了什么
代码如下:
<!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>
.瓷砖{
宽度:48px;
高度:48px;
边际:0px;
填充:0px;
浮动:左;
背景色:红色;
边框:1px纯黑;
}
函数myFunction(){
this.style.background=“#000000”;
}
函数myFunction(x){
x、 style.background=“#000000”;
}
如果您想这样做,您需要在调用函数时传递DIV元素的引用。在执行onclick处理程序期间,“this”将引用当前元素。将其作为参数传递
以下是更正后的代码:
<!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>
.瓷砖{
宽度:48px;
高度:48px;
边际:0px;
填充:0px;
浮动:左;
背景色:红色;
边框:1px纯黑;
}
函数myFunction(divObj){
divObj.style.background=“#000000”;
}
<>代码> > p>我注意到你包括jQuery。你应该强烈考虑。如果你真的走那条路线,这里会是什么样子:
<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>
.瓷砖{
宽度:48px;
高度:48px;
边际:0px;
填充:0px;
浮动:左;
背景色:红色;
边框:1px纯黑;
}
$(函数(){
$(“.tile”)。单击(函数(){
$(this.css('background-color','#000000');
});
});
示例:快速修复:myFunction(this)
…myFunction(x){x.style.
…高级修复是要使用的。还有一点需要注意的是:我看到您正在加载jquery。如果这样做,为什么不使用它呢?至少对于更改函数中的颜色,您应该使用它(检查jquery参考,但这可能是可以的)$css({backgroundColor:'#000000'})你是如何修复代码格式的?:-)对我不起作用…尽管我正确地使用了4spaces(理论上…):-)无论如何,谢谢!
<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>