将jQuery each()循环改为Vanilla JS

时间:2018-02-02 16:31:24

标签: javascript jquery arrays each

我试图将jQuery each()函数转换为vanilla javascript,我几乎就在那里,但我似乎无法找到一种存储多个实例的方法要添加到我的数组中的变量中的相同元素,然后使用替换for loop的{​​{1}}进行迭代。

我遇到的问题是将元素放在' arr'数组来表示元素的每个实例。

**请注意我已经注释掉了原始的简化each()循环,但是如果您取消对此进行评论,那么您将会看到发生了什么。

Codepen:https://codepen.io/emilychews/pen/aqdWzp

JS

each()

CSS

// // ----------  EACH LOOP ON TEXT ELEMENTS

// $('div, h1').each(function(){
//         var myElement = this;
//         myElement.style.cssText = "background: red; transition: 1s"
// });


// // ----------  VANILLA JS

var div = document.getElementsByTagName("div")[0];
var h1 = document.getElementsByTagName("h1")[0];

var arr = [div, h1];

for (i = 0; i < arr.length; i++) {

  var myElement = arr[i];
  arr[i] = this;

  myElement.style.cssText = "background: red; transition: 1s"

}

HTML

body {display: flex; margin: 20px; padding: 0; flex-direction: column; align-items: center; justify-content: center;}

div {
  width: 200px;
  height: 100px;
  background: blue;
}

h1 {
  color: white;
  background: blue;
  width: 200px;
}

3 个答案:

答案 0 :(得分:0)

问题是因为您正在创建元素的二维数组,而不是一个包含所有元素的扁平数组(这更类似于jQuery对象中保存的集合)。

要解决此问题,您可以使用querySelectorAll()获取元素,然后使用简单的forEach()循环来迭代它们。另请注意,将CSS类应用于元素而不是直接样式是更好的做法,并且需要在要转换的设置更改之前将transition规则放在元素上。试试这个:

&#13;
&#13;
[].forEach.call(document.querySelectorAll('div, h1'), function(element) {
  element.classList.add('red');
});
&#13;
body {
  display: flex;
  margin: 20px;
  padding: 0;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

div {
  width: 200px;
  height: 100px;
  background: blue;
  transition: all 1s;
}

h1 {
  color: white;
  background: blue;
  width: 200px;
  transition: all 1s;
}

.red { 
  background-color: red;
}
&#13;
<div></div>
<div></div>
<h1>a heading</h1>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

解决方案:

你在这里:

// ----------  Original Code

// $('div, h1').each(function(){
//         var myElement = this;
//         myElement.style.cssText = "background: red; transition: 1s"
// });

// ----------  VANILLA JS

const elems = document.querySelectorAll('dev,h1')

elems.forEach(e => {
  e.style.cssText = "background: red; transition: 1s"
})

说明:

  • 您不需要在vanilla js中使用this。数组中的元素引用就是元素本身!

答案 2 :(得分:0)

使用document.querySelectorAll()获取静态NodeList,然后使用NodeList.forEach()进行迭代:

var els = document.querySelectorAll("div, h1");

els.forEach(function(el) {
  el.style.cssText = "background: red; transition: 1s"
});
div {
  width: 200px;
  height: 100px;
  background: blue;
}

h1 {
  color: white;
  background: blue;
  width: 200px;
}
<div></div>
<div></div>
<h1>a heading</h1>