简体   繁体   English

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

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

If I put this.style.background="#000"; 如果我把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? 在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>

I noticed you're including jQuery. 我注意到你包括jQuery。 You should strongly consider separating your markup and JavaScript . 您应该强烈考虑将标记和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/ 示例: 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. 如果你想这样做,你需要在调用函数时传递DIV元素的引用。 During execution of your onclick handler "this" will reference to the current element. 在执行onclick处理程序期间,“this”将引用当前元素。 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>

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

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