简体   繁体   中英

JavaScript onclick Function call not working

text += "<button id=next onclick=calendar(nextDate)>"
text += "<button id=next onclick=calendar(prevDate)>"

This code does not seem to run normally. I do not know what the problem is.

function calendar(date) {  

    ...........

    text += "<tr>"
    text += "<td colspan=7>"
    text += "<button id=prev onclick=calendar(prevDate)>"
    text += "◀"
    text += "</button>"

    text += "<button id=next onclick=calendar(nextDate)>"
    text += "▶"
    text += "</button>"
    text += "</tr>"
    text += "</td>"

    text += "</table>";

    document.getElementById("cal").innerHTML = text;

}

calendar();

假设已将onClick函数设置为此功能,则在行“;”的末尾缺少分号。

Problems

 text += "<button id=prev onclick=calendar(prevDate)>" text += "<button id=next onclick=calendar(nextDate)>" 
  • You do not use quotes to surround the values of the attributes
  • You pass the strings prevDate and nextDate instead of their values, but since they don't have any quotes surrounding them, javascript will try to find these two variables, but it won't be able to (unless they're in the global scope)
  • You don not use any semicolons (;) , this probably won't cause a problem but it's still a good idea to use them

Here are a couple of ways that allow you to properly pass the previous and next date:

  • String Concatenation
  • Interpolation
  • Event Listeners

String Concatenation

text += "<button id='prev' onclick='calendar(" + prevDate + ")'>";
text += "<button id='next' onclick='calendar(" + nextDate + ")'>";

Interpolation (ES6)

text += `<button id="prev" onclick="calendar('${prevDate}')">`;
text += `<button id="next" onclick="calendar('${nextDate}')">`;

Event Listeners

text += "<button id='prev'>";
text += "<button id='next'>";

// This goes after document.getElementById("cal").innerHTML = text;
document.getElementById("prev").addEventListener("click", function (event) {
    calendar(prevDate);
});

document.getElementById("next").addEventListener("click", function (event) {
    calendar(nextDate);
});

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