javascript this的用法

2025-10-17 00:40:54

1、首先,在html中设置一个p1和一个隐藏域:

<p1 onclick="fun5(this);">点击文本!</p1>

<input type="hidden" id="hidden" value="blue">

2、接下来,定义函数fun5;fun5中应该传入一个参数,该参数可以取任一名:

<script type="text/javascript">

function fun5(a) {

var hide = document.getElementById("hidden");

if (hide.value == "blue") {

alert("bianhong");

a.style.color = "red";

hide.value = "red"

} else if (hide.value == "red") {

alert("bianlan");

a.style.color = "blue";

hide.value = "blue"

}

}

</script>

3、完整代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<script type="text/javascript">

var x = "global";

</script>

<style type="text/css">

p1 {

color: blue;

}

</style>

</head>

<body>

<p1 onclick="fun5(this);">点击文本!</p1>

<input type="hidden" id="hidden" value="blue">

<script type="text/javascript">

function fun5(a) {

var hide = document.getElementById("hidden");

if (hide.value == "blue") {

alert("变红");

a.style.color = "red";

hide.value = "red"

} else if (hide.value == "red") {

alert("变蓝");

a.style.color = "blue";

hide.value = "blue"

}

}

</script>

</body>

</html>

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
相关推荐
  • 阅读量:176
  • 阅读量:88
  • 阅读量:80
  • 阅读量:27
  • 阅读量:103
  • 猜你喜欢