簡體   English   中英

Javascript如何使函數在其他函數上工作

[英]Javascript how to make function work on other function

我剛剛開始學習JavaScript,並想嘗試一些東西。
如何使JavaScript函數在其他函數上起作用? 就像,我想當您單擊一個div時,其他div的background-color:yellow; (或JS中的x.style.backgroundColor="yellow"; ),如下所示:

<div onclick="yellow">Click me to paint the other div in yellow</div>
<div id="painted">I should be painted yellow if you click the above div!</div>

在C語言中,我知道您可以調用遞歸,所以盡管我不知道,但我還是嘗試使用它。
當然它沒有成功,但是如果您想看的話,可以使用jsbin

問:如何使用JavaScript與其他div函數一起在黃色背景上繪制div?
提前致謝。

您必須將函數附加在圓括號內,例如fillYellow()

<div onclick="fillYellow()">Click me to paint the other div in yellow</div>
<div id="painted">I should be painted yellow if you click the above div!</div>

<script>
function fillYellow(){
    document.getElementById('painted').style.background = "yellow";
}
</script>

在此函數內部,通過其ID獲取painted div,並為此div應用背景顏色。

您應該具有document.getElementById("backgroundChange"); 而不是getElementById("backgroundChange"); 它會工作:)

您的問題是“如何使JavaScript函數在其他函數上起作用?” 我開始認為也許您真的在談論做事件驅動的事情。

因此,為什么不考慮這個(稍微更高級)的解決方案

  1. 單擊<div> ,將在每個<div>處觸發一個自定義的“繪畫”事件。
    • 本身觸發的事件與其他<div>的事件不同。
  2. <div> node看到“ paint”事件e ,它將e.style應用於node.style

代碼看起來像這樣

function paintEvent(style) { // function make a custom event
    var ev = new Event('paint');
    ev.style = style;
    return ev;
}

function applyPaint(node, style) { // function to style a node
    var key;
    for (key in style) { // loop over object
        node.style[key] = style[key];
    }
}

function paintHandler(e) { // function to fire when you see a "paint" event
    applyPaint(this, e.style);
}

function clickHandler(e) { // function to fire when you see a "click" event
    var divs = document.getElementsByTagName('div'),
        i,
        paint = paintEvent({'background-color': 'yellow'});
    this.dispatchEvent(paintEvent({'background-color': 'red'}));
    for (i = 0; i < divs.length; ++i) { // loop over array-like
        if (divs[i] !== this)
            divs[i].dispatchEvent(paint);
    }
}

window.addEventListener('load', function () { // when the Window has loaded
    var divs = document.getElementsByTagName('div'),
        i;
    for (i = 0; i < divs.length; ++i) { // loop over array-like
        divs[i].addEventListener('click', clickHandler); // attach the handlers
        divs[i].addEventListener('paint', paintHandler);
    }
});

演示

您的黃色事件處理程序應查找ID為“ painted”的div,然后向其添加一個類,該類將為其顯示黃色文本。

這是一種方法(一種簡單的方法),但是還有許多其他類似的方法可以實現此目的。

暫無
暫無

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

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