简体   繁体   English

jQuery或Javascript:一周中的几天遍历数组

[英]JQuery or Javascript: iterate through array with days of the week

I am developing an app in Electron: I have 7 < div> elements for each day of the week, and they are given ids of #btn-SUNDAY, #btn-MONDAY, etc. 我正在用Electron开发应用程序:每周的每一天都有7个<div>元素,它们的ID为#btn-SUNDAY,#btn-MONDAY等。

When any of them are clicked on, these buttons should change the text property of a < p> element, with the id of #day, to whichever day of the week the user clicked on. 单击它们中的任何一个时,这些按钮应将ID为#day的<p>元素的text属性更改为用户单击的一周中的哪一天。

My guess was to iterate through an array with all 7 days, and then compare which day was equal to #btn-[i], then change #day's text property to the string at the index. 我的猜测是遍历整个7天的数组,然后比较哪一天等于#btn- [i],然后将#day的text属性更改为索引处的字符串。

While I'm able to change the text property, I always get "SATURDAY, and -1" as a result. 虽然我可以更改text属性,但结果始终是“ SATURDAY and -1”。 I am obviously doing something very wrong. 我显然做错了什么。 I could probably write this code out with if statements for each div, but I wanted to save time. 我可能可以用每个div的if语句写出这段代码,但是我想节省时间。 Ironically, I've been at this for a while, and the solution is probably dead easy, and I just don't see it. 具有讽刺意味的是,我已经有一段时间了,解决方案可能很简单,我只是看不到。

Here's my code snippet, which is included in the html page with the < div>s: 这是我的代码段,该代码段包含在html页中的<div>中:

var days = [];
days.push('SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY');

for (i in days){

  $("#btn-"+days[i]).mouseup(function() {

    $("#day").text(`${days[i]}, and ${days.indexOf(i)}`);

  })
}

I'm guessing is I need an if statement somewhere in there, but heaven help my brain, I don't know where. 我猜是在那儿的某个地方需要if语句,但是天堂可以帮助我的大脑,我不知道在哪里。

I might also be using the "for (i in x)" syntax improperly. 我可能也未正确使用“ for(i in x)”语法。 Still trying to get a feel for Javascript and JQuery. 仍在尝试了解Javascript和JQuery。

Any help is appreciated, 任何帮助表示赞赏,

-Jon -Jon

You need a closure, and using jQuery's each seems to fit here 你需要关闭,并使用jQuery的each似乎属于这里

 var days = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY']; $.each(days, function(i, day) { $("#btn-" + day).on('mouseup', function() { $("#day").text(day + ', and ' + i); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn-MONDAY">Monday</button> <button id="btn-TUESDAY">Tuesday</button> <button id="btn-WEDNESDAY">Wednesday</button> <br /><br /> <p id="day"></p> 

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

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