簡體   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