我正在尝试将 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>
Run Code Online (Sandbox Code Playgroud)
这是 JSFiddle 的东西:http : //jsfiddle.net/BH9Rs/
您需要使用document.getElementById从 id 中获取元素
function changeBackgroundColor(asdf){
document.getElementById(asdf).style.backgroundColor = "#fff000";
}
Run Code Online (Sandbox Code Playgroud)
并像这样传递id(单引号)
<button onclick="changeBackgroundColor('myDiv')">
Run Code Online (Sandbox Code Playgroud)
并在您的小提琴中将您的功能放在该Head部分中。
(在 Head 中选择 no-wrap)在左侧框架和扩展选项中