我试图将一个 div 的 id 传递给一个 javascript 函数,该函数可以做一些简单的事情,比如更改 div 的背景颜色。
奇怪的是,我的代码在 w3schools.com Tryit 编辑器中有效,但在 JSFiddle 中无效。它在我的编译器 (Coda 2) 中也不起作用。
这是否是正确的处理方式?这是我的代码:
<!DOCTYPE html>
<html>
<head>
<script>
function changeBackgroundColor(asdf)
{
asdf.style.backgroundColor = "#fff000";
}
</script>
</head>
<body>
<div id="myDiv" style="background:red"> this is my div </div>
<button onclick="changeBackgroundColor(myDiv)"> Set background color </button>
</body>
</html>
这是 JSFiddle 的东西:http://jsfiddle.net/BH9Rs/
最佳答案
您需要使用document.getElementById
从id 中获取元素
function changeBackgroundColor(asdf){
document.getElementById(asdf).style.backgroundColor = "#fff000";
}
并像这样传递 id(用单引号引起来)
<button onclick="changeBackgroundColor('myDiv')">
然后在您的 fiddle 中将您的函数放入 Head
部分。
(在 Head 中选择 no-wrap)在左侧框架和扩展选项
关于javascript - 将 div 传递给 javascript 函数并更改其样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19435302/