Changing element first child is not working with setTimeout

时间:2017-08-30 20:03:21

标签: javascript

I am working on a project which has a div with certain children. I want to change first element(s) background color by a variable. For example, if I have 32 children div and variable is 20, the function must be change first 20 divs background color.

I used loaderLabel1.setVisible(false); method by this.

My code is like,

actionPerformed

It works in import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class TestLoader extends JPanel{ static ImageIcon loading1 = new ImageIcon("D:\\WORKSPACE\\STUDY\\images\\ajax-loader.gif"); static JLabel loaderLabel1 = new JLabel(loading1, JLabel.CENTER); public TestLoader(){ super(new GridLayout(0, 1)); System.out.println("---------TEST ------"); JPanel submitPanel = new JPanel(); submitPanel.add(clearMessageButton); this.add(submitPanel); JPanel LOADER_PANEL = new JPanel(); loaderLabel1.setVisible(false); LOADER_PANEL.add(loaderLabel1); this.add(LOADER_PANEL); } JButton clearMessageButton = new JButton(new AbstractAction("Test Result") { @Override public void actionPerformed(ActionEvent arg0) { loaderLabel1.setVisible(true); TestMethod(); loaderLabel1.setVisible(false); }}); public void TestMethod(){ System.out.println(" =========START TestMethod ========="); try { Thread.currentThread().sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(" =========complete TestMethod ========="); } /** * @param args */ public static void main(final String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { TestLoader pf = new TestLoader(); pf.display(); } }); } private void display() { JFrame frame = new JFrame("TEST LOADER"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(this); frame.pack(); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } } but I must use parent.children in this function. If I use function change() { var parent = document.getElementById("clock"); var child = parent.children; var howMany = 5; for (var i=0; i < howMany; i++){ if (child[i].tagName == "DIV") { child[i].style.backgroundColor = "red"; } } } , I get window.onload error.

So, what is wrong in my function? Is there a other way to do it?

By the way, I'm pretty much new at Javascript and this is my first question on Stack Overflow.

2 个答案:

答案 0 :(得分:0)

From what I can tell your code is ok. I've tested the following HTML/CSS in this Codepen and the function is operating fine: https://codepen.io/anon/pen/gxZwGd?editors=1111

>

The first 5 ['id', 'code', 'name', 'area', 'area_land', 'area_water', 'population', 'population_growth', 'birth_rate', 'death_rate', 'migration_rate', 'created_at', 'updated_at'] s are changing to red, while the others remain blue. And without any console errors.

You may have a made a mistake in your HTML markup. It would be helpful if you added the markup to your question.

答案 1 :(得分:0)

我假设您正在寻找更改div之间的间隔颜色。我不是100%肯定这是你想要实现的目标,但我希望它对你有所帮助。

function changeColor(elements) {
  // Remove the item at index 0 from the array.
  var firstElement = elements.shift();
  // Check if the element is a div element...
  if (firstElement.tagName === 'DIV') {
    // and if it is add a class to change its background color.
    firstElement.classList.add('activated');
  }
  // Check if the array is empty, when it is we don't have to perform any more actions.
  if (elements.length === 0) {
    return;
  }
  
  // Wait a second before calling this method again with the array (which now has 1 less item in it).
  setTimeout(() => {
    changeColor(elements);
  }, 1000);
}

function change() {
    // Get the parent element.
    var parent = document.getElementById("clock"),
        // Get the number of divs to change.
        howMany = 5,
        // Get the children from the parent element, convert it to an array and take as many as needed elements (staring at the first element).
        children = Array.from(parent.children).slice(0, 5);

    // Call the change colors method.
    changeColor(children);
}

change();
#clock {
  display: flex;
}

#clock > div {
  background-color: blue;
  height: 20px;
  width: 20px;
}

#clock > div + div {
  margin-left: 10px;
}

#clock > div.activated {
  background-color: red;
}
<div id="clock">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>  
  <div></div>
  <div></div>
  <div></div>
  <div></div>  
</div>

如果我是你,我会改变你如何改变元素。而不是通过父的子属性获取它们,直接从DOM中获取它们(假设您可以为可能必须更改的div分配类名):

elements = parent.querySelector('.my class name');

您可以安全地将标记名称与div进行比较,这是我试图避免的解决方案。这也意味着如果你选择5个项目,你肯定它将是5个需要改变的项目。