search

Home  >  Q&A  >  body text

How to display the current day of the week on a button?

Is it possible to automatically display the day of the week on a button?

Please refer to the markup below, I need to make "Monday" display as the current day of the week.

1

<button class="button">征服星期一</button>

P粉738676186P粉738676186583 days ago708

reply all(2)I'll reply

  • P粉757556355

    P粉7575563552023-09-08 19:10:43

    Can you use this js code to use Date().getDay() to return the day of the week between 0 and 6 and use the weekdays list to represent the day of the week?

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    //获取具有id的按钮

      const button = document.getElementById("dayButton");

      //星期几的数组

      const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];

      //当前星期几的索引

      const currentDayiIndex = new Date().getDay();

      //点击按钮显示星期几

        dayButton.addEventListener("click",()=>{

            day.innerHTML = weekdays[currentDayiIndex]

            button.innerHTML = "征服" + weekdays[currentDayiIndex];

            })

    1

    2

    <button class="button" id="dayButton">显示星期几</button>

    <p id="day"></p>

    hope this helps

    reply
    0
  • P粉662614213

    P粉6626142132023-09-08 12:11:41

    You can use Date::toLocaleDateString to display the current day of the week:

    1

    document.querySelector('.button').textContent = '征服 ' + new Date().toLocaleDateString('en-us', {weekday:'long'});

    1

    <button class="button"></button>

    reply
    0
  • Cancelreply