gpt4 book ai didi

javascript - "this"用在函数括号里有什么作用?

转载 作者:行者123 更新时间:2023-11-28 04:19:04 25 4
gpt4 key购买 nike

我有一个包含三个按钮的简单页面。我想创建一个功能,通过单击更改页面的背景颜色。所以我以某种方式使它起作用。

当我在变色括号中使用它时,我基本上想知道“this”究竟做了什么?

我有点感觉它的作用,但我需要更多客观知识。

我的 HTML:

<!DOCTYPE html>
<html>
<head>
<title>Panel</title>
<link rel="stylesheet" type="text/css" href="style.css"></link>
<script src="javascript.js"></script>
</head>

<body>
<h1>THIS IS SOME TEXT</h1>
<h2>This is some more text</h2>
<button class="buttons" id="button1" onclick="changecolor(this)">;P</button>
<button class="buttons" id="button2" onclick="changecolor(this)">;]</button>
<button class="buttons" id="button3" onclick="changecolor(this)">;)</button>
</body>
</html>

我的CSS:

    h1{
background-color: blue;
float: left;
}

h2{
color: blue;
float: left;
width:100%;

}

.buttons{
float:left;
margin-right: 10px;
width: 25px;
height: 25px;

}

#button1{
background-color:green;
}

#button2{
background-color:darkgray;
}

#button3{
background-color:blue;
}

我的javascript:

function changecolor(clickedButton){

if(clickedButton.id == "button1"){
document.body.style.backgroundColor="lightgreen";

}

if(clickedButton.id =="button2"){
document.body.style.backgroundColor="gray";
}

if(clickedButton.id =="button3"){
document.body.style.backgroundColor="lightblue";
}
}

提前致谢!

最佳答案

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. An onclick property, though, is owned by the HTML element it belongs to.

通过- http://www.quirksmode.org/js/this.html

关于javascript - "this"用在函数括号里有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29153894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com