2 回答
TA贡献1825条经验 获得超4个赞
您的代码中的问题可能与选择有关。当您使用时,getElementsByClassName您将获得一个元素数组,而不是单个元素。因此,如果您将使用document.getElementsByClassName("hola")[0],您将获得您的元素。
我认为您应该使用id而不是className,因为当您使用时,document.getElementsByClassName("abc")您将获得同一类的元素数组。由于您在 2 个不同的页面中使用它,并且可能对其他元素也使用相同的类,因此数组的顺序可能不同,并且很难找到您的按钮。
用于document.getElementById("someID")获取特定元素,并对id两个按钮使用相同的元素(因为它们位于不同的页面上,这应该不是问题)。
let button = document.getElementById("myRedBodyButton");
button.addEventListener('click', function() {
document.body.classList.add("red");
});
.red {
background: red
}
<button id="myRedBodyButton">clickMe</button>
TA贡献1789条经验 获得超10个赞
这是你要找的吗?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="hello">BTN 1</button>
<script>
var ccc = document.querySelector("button#hello")
ccc.addEventListener('click', function() {
document.body.style.backgroundColor = 'red';
})
</script>
</body>
</html>
添加回答
举报
