简体   繁体   English

一次将功能应用于多个元素

[英]Apply a function to several elements at once

When I apply the same function to several elements, I usually do the following: 当我将相同的功能应用于多个元素时,通常会执行以下操作:

var func = function(elem) {
  elem.style.color = 'red';
};

var p = document.querySelector('p');
var div = document.querySelector('div');

func(p);
func(div);

I was wondering if there is an easy way to apply this function to two (or more) elements at once ? 我想知道是否有一种简单的方法一次将此功能应用于两个(或多个)元素? Eg : 例如:

func(p, div); // Apply my function to both elements at once

You can make use of arguments : 您可以使用arguments

var func = function() {
    var args = [].slice.apply(arguments);

    args.forEach(function (elem) {
        elem.style.color = 'red';
    });
};

Call it like you wanted: 随意调用它:

func(p, div);

On a side note, there is a functionality called "rest parameter" planned in ECMAScript 6 that allows for just what you had in mind, take a look here . 附带说明一下,在ECMAScript 6中计划了一种称为“休息参数”的功能,该功能可以让您记住自己的想法,请在此处查看

Transforming the function so it returns itself 转换函数,使其返回自身

By transforming the function so it returns itself, you can use the syntax 通过转换函数使其返回自身,可以使用以下语法

func(p)(div)

To make this work, you'll need to arrange for func to return itself. 要使此工作正常进行,您需要安排func返回自身。

function selfify(fn) {
    return function self() {
        fn.apply(this, arguments);
        return self;
    };
}

Then 然后

funcx = selfify(func);
funcx(p)(div);

Transforming the function so it is called on each argument 转换函数,以便在每个参数上调用它

If you would prefer the func(p, div) syntax, write the following kind of transformer, which creates a function which calls an underlying function on each of its arguments: 如果您更喜欢func(p, div)语法,请编写以下类型的转换器,该转换器创建一个函数,该函数在其每个参数上调用基础函数:

function repeatify(fn) {
    return function() {
        Array.prototype.forEach.call(arguments, fn, this);
    };
}

Then 然后

funcy = repeatify(func);
funcy(p, div);

This obviously won't work well if the underlying function takes two or more parameters. 如果基础函数接受两个或多个参数,则这显然不能很好地工作。

In ES6, using rest parameters, the above can be written somewhat more simply as 在ES6中,使用rest参数,可以将上面的内容写得更简单:

function repeatify(fn) {
    return function(...args) {
        [...args].forEach(fn, this);
    };
}

Real simple solution 真正简单的解决方案

If all the above functional-style programming is too much to wrap your head around, all you really need to do is: 如果以上所有函数式编程都太多了,您真的需要做的就是:

[p, div].forEach(func);

You could combine some of the great answers here to come up with a functionnal programming code easily reusable : 您可以在此处结合一些很好的答案,以得出易于重用的函数式编程代码:

var f = function (applyTo) {
    var makeArray = function(arrayLike) {
        return Array.prototype.slice.call(arrayLike);
    };
    return function () {
        var args = makeArray(arguments),
            elements = [];
        args.forEach(function (selector) {
            var newElements = makeArray(document.querySelectorAll(selector));
            console.log(newElements);
            elements = elements.concat(newElements);
        });
        elements.forEach(applyTo);
    }
};

var redify = function (elem) {
    elem.style.color = '#F00';
}

var underline = function (elem) {
    elem.style.textDecoration = 'underline';
}

var overline = function (elem) {
    elem.style.textDecoration = 'overline';
}

f(redify)('div', 'p');

f(underline)('div.test2');

f(overline)('p.test2');

JSFiddle JSFiddle

var forEach = Array.prototype.forEach;
var elms = document.querySelectorAll('p, div'); // css selector to match both p & div
var func = function(elem) {
    elem.style.color = 'red';
};

forEach.call(elms, func);

Consider combining a basic loop from the previous answers and the use of classes instead of querySelector. 考虑结合先前答案的基本循环以及使用类而不是querySelector。

Thus you could assign the needed classed to all your element that you'll need to pass through the function and then just call the function with them: 因此,您可以将所需的类分配给通过该函数传递所需的所有元素,然后仅用它们调用该函数:

var func = function (elem) {
    for (var i = 0; i < elem.length; i++) {
        elem[i].style.color = 'red';
    }
};

func(document.getElementsByClassName("yourClass"));

The right way to do is through the use of classes. 正确的方法是通过使用类。

<p class="myClass"></p>
<div class="myClass"></div>

Then in your javascript when you wish to change the color of these two elements, simply do: 然后,当您希望更改这两个元素的颜色时,只需执行以下操作:

var elems = document.getElementsByClassName("myClass");

for(var i=0; i<elems.length; i++){
    func(elem[i]);
}

It'll be useful for long run when you have large number of elements, organizing them in classes based on your needs is the way to go. 当您有大量元素时,这对于长期运行很有用,您可以根据需要将它们组织在类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM