Js从循环中提取目标并在外部进行处理

时间:2018-10-21 13:55:49

标签: javascript arrays

我希望能够从循环中提取值并在外部进行处理。

在实践中,我希望所有“橙色”(但仅评估最后一个)

let classes = Array.from(document.getElementsByClassName("testY"));
classes.forEach(function (looped, i) {
        loopclass = looped;
        loopclass.style.color = "blue";
        return loopclass;
});
loopclass.style.color = "orange";

但是只有最后一堂课变成橙色...我该如何在不呆在里面的情况下进行回收?


----编辑1

基于上述内容,我希望能够以某种方式恢复这些类并使其循环工作。

这是来自建议的另一个示例:

let classeslist = Array.from(document.getElementsByClassName("testY"));
let classes = classeslist.map( (el) => {
        loopedclass = el;
        return loopedclass
});
loopedclass.style.color = "orange";

即使在这里,也只收集最后一个类并返回。


----编辑2.B

好的,它开始成型。

这个想法可行,但是仍然存在链接问题。

我试图插入FrankerZ的构造函数(元素),但是,当然,将我锁定在某些东西上。

现在的问题是关于libs ...如何连接函数的结果?

LIBS:

actions = {

    showError: (elem) => {
        elem.style.color = 'red';
    },
    highlight: (elem) => {
        elem.style.color = 'orange';
        elem.style.fontSize = '1.2em;';
    }
}

class Core {

    find(subject) //work
    {
        let name;

        if (subject.startsWith("#")) {
           ...
        }
        if (subject.startsWith(".")) {
            name = subject.split(".")[1];
            find = [...document.getElementsByClassName(name)];
        }
        if (subject.startsWith("[")) {
           ...
        }
        return find;
    }

    actionfor(target, todo) //work
    {
        target.forEach(actions[todo]);
    }

    loop(todo)
    {
        alert("direct todo");
        ???.forEach(actions[todo]);
    }
}
const core = new Core();

脚本:

(function () {

       //indirect action // woooork!
       var X = core.find(".test_X");
       core.actionfor(X, "showError");

       //direct action //f**k!
       core.find(".test_Y").loop("highlight");
})();

HTML:

<div class="test_X">SIMPLE TEST CLASS</div>
<div class="test_X">SIMPLE TEST CLASS</div>
<div class="test_X">SIMPLE TEST CLASS</div>
<div class="test_Y">SIMPLE TEST CLASS</div>
<div class="test_Y">SIMPLE TEST CLASS</div>
<div class="test_Y">SIMPLE TEST CLASS</div>

2 个答案:

答案 0 :(得分:3)

classes是一个数组,因此,如果需要最后一个,只需通过索引即可访问它:

let classes = Array.from(document.getElementsByClassName("testY"));

classes[classes.length - 1].style.color = 'orange';
<span class="testY">Testing 1</span>
<span class="testY">Testing 2</span>
<span class="testY">Testing 3</span>

要回答您的其他问题,正如我在上文.forEach中所解释的,此处没有您所需要的。而是使用.map()将元素映射到数组(在这种情况下,每个元素的样式)。在这里,我将它们全部设置为蓝色,然后返回el.style供以后使用。 (在下一种情况下,将最后一种颜色设置为橙色):

let classes = Array.from(document.getElementsByClassName("testY"));

let styles = classes.map((el) => {
  el.style.color = 'blue';
  
  return el.style;
});

styles[styles.length - 1].color = 'orange';
<span class="testY">Testing 1</span>
<span class="testY">Testing 2</span>
<span class="testY">Testing 3</span>

有关如何.doSomething()的示例:

class LibElementHelper {
  constructor(elements) {
    this.elements = elements;
  }
  
  doSomething() {
    this.elements.forEach((el) => el.style.color = 'blue');
  }
}

class MyLib {
  getClass(className) {
    let classes = Array.from(document.getElementsByClassName(className));
    
    return new LibElementHelper(classes);
    
    //Or simply:
    return {
      doSomething: () => classes.forEach((el) => el.style.color = 'blue')
    };
  }
}

var lib = new MyLib();

lib.getClass("testY").doSomething();
<span class="testY">Testing 1</span>
<span class="testY">Testing 2</span>
<span class="testY">Testing 3</span>

答案 1 :(得分:1)

您的以下代码:

let classeslist = Array.from(document.getElementsByClassName("testY"));
let classes = classeslist.map( (el) => {
        loopedclass = el;
        return loopedclass
});
loopedclass.style.color = "orange";

即使在这里,也只收集最后一个类并返回。

不, 返回所有类(准确地说,不是元素)。 您根本不需要该map函数,因为它绝对不执行任何操作。 它返回与map funciton参数相同的元素。 (它什么都不做)。 映射函数应该从数组中获取值并将其更改(将它们映射)为其他值。

一种做自己想做的事情的方法...也许。

// list of shared actions that can be used everywhere
Actions = {
  showError: (elem) => {
    elem.style.color = 'red';
  },
  clearError: (elem) => {
    elem.style.color = 'black';
  },
  hide: (elem) => {
    elem.style.display = 'none';
  },
  reveal: (elem) => {
    elem.style.display = 'block';
  },
  highlight: (elem) => {
    elem.style.color = 'orange';
    elem.style.fontSize = '1.2em;';
  } ,
  underline: (elem) => {
    elem.style.textDecoration = 'underline';
  }
}
// connect actions to classes
class ClassActions {
    action(className, action) {
      [...document.getElementsByClassName(className)].forEach(Actions[action]);
      return this;
    }
}
const classActions = new ClassActions();
// Use the class actions when buttons are clicked
function commentError() {
  classActions.action('comment', 'showError');
}
function commentHide() {
  classActions.action('comment', 'hide');
}
function commentReveal() {
  classActions.action('comment', 'reveal');
}
function commentHighlight() {
  classActions.action('comment', 'highlight');
}
function postHighlightAndUnderlineAndRemoveComments() {
  classActions
  .action('post', 'highlight')
  .action('post', 'underline')
  .action('comment', 'hide');
}
.post {
  padding: 2em;
}
.comment {
  color: gray;
  margin: 1em;
}
<div class='post'>Post 1</div>
<div class='comment'>Comment 1</div>
<div class='comment'>Comment 2</div>
<div class='comment'>Comment 3</div>

<div class='post'>Post 2</div>
<div class='comment'>Comment 1</div>
<div class='comment'>Comment 2</div>
<div class='comment'>Comment 3</div>

<button onclick="commentError()">comment error</button>
<button onclick="commentHide()">comment hide</button>
<button onclick="commentReveal()">comment reveal</button>
<button onclick="commentHighlight()">comment highlight</button>
<button onclick="postHighlight()">post highlight</button>

<button onclick="postHighlightAndUnderlineAndRemoveComments()">Highlight and underline and...</button>

我认为您实际上根本不应该使用任何功能来更改样式。 首先-您应该尝试仅使用CSS解决问题。然后,当您需要更高级的解决方案时,可以尝试使用javascript。

例如,如果您想将一个类的元素更改为“橙色”,则可以通过向其添加另一个类来实现。

在CSS中,样式会覆盖其他样式。因此,要使动作赋予元素特定的样式,请尝试使用此方式。

// CSS
.comment {color: black;}
.comment.error { opacity: 0.8; color: red; }

// JS
[...document.getElementsByClassName("comments")].forEach((e) => {
    e.classList.add('error');
});