简体   繁体   English

querySelectorAll对指定元素不起作用

[英]querySelectorAll not working for specified elements

I'm trying to achieve to select all specified elements that i want using looped querySelectorAll but I'm still failing. 我正在尝试使用循环的querySelectorAll选择我想要的所有指定元素,但仍然失败。 Only the first element is always selected. 始终仅选择第一个元素。 Here is my code: 这是我的代码:

HTML: HTML:

<div id="text">Text 1</div>
<div id="text">Text 2</div>
<div id="text">Text 3</div>


JS: JS:

function query(selector) {
    var elem = document.querySelectorAll(selector);

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

query("#text").style.background = "red";


What have I done wrong? 我做错了什么?

The return statement terminates the function execution, ie the subsequent code is not executed. return语句终止函数执行,即不执行后续代码。 Your function returns the first selected element in the first iteration of the loop and that's the end of it. 您的函数将在循环的第一次迭代中返回第一个被选择的元素,这就是它的结束。

In this case there is no need to iterate the collection. 在这种情况下,无需迭代集合。 If you want to get all the selected elements you can return the returned value of the querySelectorAll method, but then you can't use the style property that way as the returned collection doesn't have such property. 如果要获取所有选定的元素,则可以返回querySelectorAll方法的返回值,但是由于返回的集合没有这种属性,因此不能使用style属性。

function query(selector) {
    // convert the NodeList into a regular array
    // https://developer.mozilla.org/en-US/docs/Web/API/NodeList
    return Array.prototype.slice.call(document.querySelectorAll(selector));
}

// since `query` returns an array you can use it's `forEach` method 
// for iterating over the array
query(".text").forEach(function(el) {
   el.style.backgroundColor = "red";
});

Note that IDs must be unique. 请注意,ID必须是唯一的。 You should use classes instead. 您应该改用类。

The problem is in the return statement, which only returns first element and then applies the chain to it. 问题出在return语句中,该语句仅返回第一个元素 ,然后对其应用链。 After that it is finished and no more elements get processed. 之后,它不再处理任何其他元素。


You can use this hack and have a truly universal applicator . 您可以使用此技巧,并拥有真正的通用涂药器

function query(selector, callback) {
  [].forEach.call(document.querySelectorAll(selector), callback)
}

And this is how to use it. 这就是如何使用它。

query('#option', function(el){el.style.backgroundColor = "red"})
// or ES6
query('#option', el => el.style.backgroundColor = "blue")

Apply several changes at once: 一次应用多个更改:

query('#option', el => {
  el.style.backgroundColor = "green"
  el.style.color = 'cyan'
  el.style.textDecoration = 'line-through'
})



Or mimick chaining , if you want to be nasty for whatever reason... mimick chaining ,如果您出于任何原因想要讨厌...

function query(selector, callback) {
  [].forEach.call(document.querySelectorAll(selector), callback) 

  return arguments.callee.bind(undefined, selector)
}

usage: 用法:

query('#option', el => el.style.backgroundColor = 'red')(el => el.style.color = 'black')(el => el.style.textDecoration = 'underline')

Use class instead of id -- Ids have to be unique, but classes can be assigned to as many element as you want and you can assign as many classes to each element as well, so 使用class而不是id -ID必须是唯一的,但是可以将类分配给所需的任意多个元素,也可以为每个元素分配尽可能多的类,因此

<div class="mytext">Text 1</div>
<div class="mytext">Text 2</div>
<div class="mytext">Text 3</div>

And I suggest you use Jquery instead, so you can do the background color as 我建议您改用Jquery,这样就可以将背景颜色设置为

$(".mytext").css({background:"red"});

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

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