简体   繁体   English

JavaScript Second for循环永远不会执行

[英]Javascript Second for loop never executes

I have a script that hides or shows an element after a number of seconds have elapsed. 我有一个脚本,可以在几秒钟后隐藏或显示一个元素。 The elements are all give the class .show-after-x-seconds or .hide-after-x-seconds and an attribute called data_seconds with the number of seconds. 所有元素都提供了类.show-after-x-seconds.hide-after-x-seconds以及名为data_seconds的属性,其中包含秒数。

The first loop iterates through all the elements with that class but the second loop seems to be ignored. 第一个循环遍历该类的所有元素,但第二个循环似乎被忽略。 I tried switching their order and only the first loop executes. 我尝试切换它们的顺序,仅执行第一个循环。

<div class="hide-after-x-seconds" data_seconds="2">
    <img src="/static/img1.png">
</div>
<div class="show-after-x-seconds" style="display: none" data_seconds="4">
    <img src="/static/img2.png">
</div>

var show_these = $('.show-after-x-seconds');
for(var show in show_these) {
    show_this(show_these[show], parseInt(show_these[show].attributes.data_seconds.value));
}
var hide_these = $('.hide-after-x-seconds');
for(var hide in hide_these) {
    hide_this(hide_these[hide], parseInt(hide_these[hide].attributes.data_seconds.value));
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
function hide_this(element_to_hide, x){
    sleep(x *1000).then(() => {
        element_to_hide.style.display = 'none';
    })
}
function show_this(element_to_show, x){
    sleep(x *1000).then(() => {
        element_to_show.style.display = 'block';
    })
}

This will tell you what you're doing wrong: 这将告诉您您在做什么错:

var hide_these = $('.hide-after-x-seconds');
for(var hide in hide_these) {
    console.log(hide_these[hide]);
}

You want to do 你想做

$('.hide-after-x-seconds').each(function() {
   hide_this(this,this.getAttribute('data-seconds'));
});

Also, change your attribute data_seconds to data-seconds . 另外,将属性data_seconds更改为data-seconds It'll still work, but data_seconds is a non-standard attribute. 它仍然可以使用,但是data_seconds是非标准属性。 You'll want to use HTML5 data- attributes . 您将要使用HTML5 data-属性

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

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