簡體   English   中英

將div傳遞給javascript函數並更改其樣式

[英]Pass div to javascript function and change its style

我正在嘗試將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')"> 

然后在您的小提琴中將您的功能放在Head部分中。 (在頭中選擇不換行)在左側的“框架和擴展”選項

Js小提琴演示

將腳本放置組合更改為no wrap - in <head> (左側面板上的第二個組合框)

myDiv是未知標識符。

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

<button onclick="changeBackgroundColor(document.getElementById('myDiv'))"> Set background color </button>

此外,由於jsFiddle環境,您還必須在HTML中移動JS代碼: http : //jsfiddle.net/BH9Rs/1/

<script>
    function changeBackgroundColor(asdf) {
        asdf.style.backgroundColor = "#fff000";
    }
</script>
<div id="myDiv" style="background:red">this is my div</div>
<button onclick="changeBackgroundColor(document.getElementById('myDiv'))">Set background color</button>

內聯樣式和內聯點擊事件? 噓。

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM