将div传递给javascript函数并更改其样式

将div传递给javascript函数并更改其样式,javascript,html,Javascript,Html,我试图将一个div的id传递给一个javascript函数,该函数执行一些简单的操作,比如更改div的背景颜色 奇怪的是,我的代码在w3schools.com Tryit编辑器中工作,但在JSFiddle中不工作。它在我的编译器(Coda 2)中也不起作用 这样做对吗?这是我的密码: <!DOCTYPE html> <html> <head> <script> function changeBackgroundColor(asdf) { a

我试图将一个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>

功能更改背景颜色(asdf)
{
asdf.style.backgroundColor=“#fff000”;
}
这是我的部门
设置背景色

这里是JSFiddle的内容:

您需要使用
document.getElementById
从id获取元素

function changeBackgroundColor(asdf){
    document.getElementById(asdf).style.backgroundColor = "#fff000";
}
然后像这样传递id(用单引号)


在你的小提琴中,把你的函数放在
标题中。
(在左侧框架和延伸选项中选择“头部不包裹”)


myDiv
是未知标识符

使用
document.getElementById()
引用您的div:

<button onclick="changeBackgroundColor(document.getElementById('myDiv'))"> Set background color </button>
设置背景色
此外,由于JSFIDLE环境,您必须在HTML中移动JS代码:


功能更改背景颜色(asdf){
asdf.style.backgroundColor=“#fff000”;
}
这是我的部门
设置背景色

将脚本放置组合更改为
不换行
(左面板上的第二个组合框)

内联样式和内联单击事件?嘘

<div id="myDiv"> this is my div </div>
<button id="clickMe"> Set background color </button>

<script>
    document.getElementById('clickMe').onclick = function(){
        document.getElementById('myDiv').style.backgroundColor = '#fff000';
    }
</script>
这是我的部门
设置背景色
document.getElementById('clickMe')。onclick=function(){
document.getElementById('myDiv').style.backgroundColor='#fff000';
}
您必须这样做:

    <!DOCTYPE html>
<html>
<head>
<script>
function changeBackgroundColor(asdf)
{
    document.getElementById(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>

功能更改背景颜色(asdf)
{
document.getElementById(asdf).style.backgroundColor=“#fff000”;
}
这是我的部门
设置背景色

旧的DOM事件?喝倒采:D@ComFreek是的,我想我应该做一些小步骤,而不是显示
addEventListener
attachEvent
语法。
<div id="myDiv"> this is my div </div>
<button id="clickMe"> Set background color </button>

<script>
    document.getElementById('clickMe').onclick = function(){
        document.getElementById('myDiv').style.backgroundColor = '#fff000';
    }
</script>
    <!DOCTYPE html>
<html>
<head>
<script>
function changeBackgroundColor(asdf)
{
    document.getElementById(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>