简体   繁体   English

JavaScript事件处理程序不起作用

[英]JavaScript event handler not working

This javascript: 这个javascript:

window.onload=init;

function init(){
    var addSongButton = document.getElementById("addButton");
    addSongButton.onclick = handleAddSongButtonClick;
}

function handleAddSongButtonClick(){
    var textInput = document.getElementById("songTextInput");
    var songName = textInput.value;

    if(songName=""){
        alert("Please enter a song name");
    }
    else{
    alert("Adding " +songName);
    }
}

is linked to this HTML: 链接到此HTML:

<form>
  <input type="text" id="songTextInput" size="40" placeholder="Song name">
  <input type="button" id="addButton" value="Add Song">
</form>

<ul id="playlist">

</ul>

Why whenever I enter a song name or don't enter a song name it just alerts "Adding"? 为什么每当我输入歌曲名称或不输入歌曲名称时,它只会提醒“添加”? I want it to alert "Adding insert song name " when text is entered and alert "Please enter a song name" when text is not entered. 我希望它在输入文本时提醒“添加插入歌曲名称 ”,并在未输入文本时提示“请输入歌曲名称”。

You are using an equals sign in your if() check, here: 您在if()检查中使用等号,此处:

if(songName=""){

That is setting `songName' to be an empty string. 那就是将`songName'设置为空字符串。 Change the code to: 将代码更改为:

if (songName === "") {

. . . and that should do the comparison correctly. 这应该正确地进行比较。

You're using the assignment operator, = , in your if statement: 您在if语句中使用赋值运算符=

if(songName="")

where you should be using either == or === to actually compare the values. 您应该使用=====来实际比较这些值。 (see this for the difference between these) (见这些差异)

What's happening currently is that songName="" is being evaluated, and returns "" (the value that was assigned). 目前正在发生的事情是正在评估songName="" ,并返回"" (已分配的值)。 This is a falsey value meaning it is interpreted as false and so your coniditonal statement is falling through to your else but with songName now being equal to the empty string. 这是一个假值,意味着它被解释为false ,所以你的coniditonal语句正在落入你的else但是songName现在等于空字符串。

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

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