我无法通过简单的功能更改按钮的颜色,颜色根本不会改变.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="JavaScript">
function changeColor(){
document.getElementsByTagName('button').style.backgroundColor="green";
}
</script>
</head>
<body >
<form action="/action_page.php" method="get" name="form1">
<input type="text" id="campoDeFlores">
<button type="button" onclick="changeColor()" name="1">1</button>
<button type="button" name="2">2</button>
<button type="button" name="3">3</button>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
知道为什么它不起作用吗?
document.getElementsByTagName返回元素列表而不是单个元素。您需要将其转换为数组,Array.from然后使用Array.map
function changeColor(){
Array.from(document.querySelectorAll('button')).map(function(button) {
button.style.backgroundColor="green";
})
}
Run Code Online (Sandbox Code Playgroud)