简体   繁体   中英

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.

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.

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.

While I'm able to change the text property, I always get "SATURDAY, and -1" as a result. 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. 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:

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.

I might also be using the "for (i in x)" syntax improperly. Still trying to get a feel for Javascript and JQuery.

Any help is appreciated,

-Jon

You need a closure, and using jQuery's each seems to fit here

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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