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