繁体   English   中英

如何通过在JavaScript中调用函数来更改onclick的颜色?

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

如果我把this.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>

我注意到你包括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>

示例: http //jsfiddle.net/6zAN7/9/

如果你想这样做,你需要在调用函数时传递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> 
<div class="tile" onclick="myFunction(this)"></div>

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

暂无
暂无

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

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