简体   繁体   English

处理由 ID 选择的单个元素和由类选择的多个元素的 JavaScript 函数

[英]JavaScript function that process both single element selected by ID and multiple elements selected by class

I would like to write a JS generic function that can process indifferently a single element selected by its ID or multiple element selected by class.我想编写一个 JS 通用函数,它可以无差别地处理由其 ID 选择的单个元素或由类选择的多个元素。

var el1 = document.getElementById('myId');
myFunction(el1)
var el2 = document.getElementsByClassName('myClass');
myFunction(el2)

My problem is to write the function.我的问题是写函数。 I started something like:我开始了类似的事情:

function myFunction(el) {
    if (typeof el == undefined) process(el);
    else {
        for (let i=0 ; i<el.length ; i++)
            process(el[i]);
    }
}

I'm not really confident in this solution:我对这个解决方案不太有信心:

  • not sure about the test ( typeof ... == undefined )不确定测试( typeof ... == undefined
  • not sure about the loop, map should probably be a better option不确定循环, map应该是更好的选择

Since this should be something commonly used, I'm convinced that some of you has already think to the best way to write this code.既然这应该是常用的东西,我相信你们中的一些人已经想到了编写这段代码的最佳方式。

You can probably just accomplish this via a wrapper for the querySelectorAll() function, which is a built-in function used to easily query the DOM:您可能只需通过querySelectorAll()函数的包装器即可完成此操作,该函数是用于轻松查询 DOM 的内置函数:

function myFunction(selector) {
    return document.querySelectorAll(`#${selector}`) || document.querySelectorAll(`.${selector}`);
}

This will return aNodeList of the matching elements (first checking for a given id attribute and if that fails, attempting to find any elements sharing the same name as a class attribute).这将返回匹配元素的NodeList (首先检查给定的id属性,如果失败,则尝试查找与class属性共享相同名称的任何元素)。

So if you wanted to perform some process, you could simply throw an iterator on the result if one exists and perform it against each element:因此,如果您想执行某个过程,您可以简单地在结果上抛出一个迭代器(如果存在)并针对每个元素执行它:

function myFunction(selector) {
     let nodes = document.querySelectorAll(`#${selector}`) || document.querySelectorAll(`.${selector}`);
     if(nodes) {
         for (var i = 0, i < nodes.length; i++) {
             process(nodes[i]);
         }
     }
}

Example例子

 function myFunction(selector) { return document.querySelectorAll(`#${selector}`) || document.querySelectorAll(`.${selector}`); }
 <div id='id'>id</div> <div class='class'>class</div> <br /> <button onclick='alert(myFunction("id"));'>Find By ID</button> <button onclick='alert(myFunction("class"));'>Find By Class</button>

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

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