为什么我的外部 javascript onclick 不工作

Why is my External javscript onclick not working

我创建了一个 Javascript 代码,允许一个人 select 是查看密码还是隐藏密码 它。在我决定制作 Javascript external.now 之前,一切都运行良好,当我单击显示按钮时它没有响应。 可能是什么问题? HTML

<input type="password" id="password" oninput="display()" 
placeholder="Password">
<div id='disp'></div>

JAVASCRIPT

function display(){
var button=document.getElementById('password').value;
var button2=document.getElementById('password');

if(button.length>0 && button2.type==='password')
{
    document.getElementById('disp').innerHTML="<button  id='show' 
class='buton'onclick='myFunction()'><b>SHOW</b></button>";

}
else if(button.length>0 && button2.type==='text')
{
    document.getElementById('disp').innerHTML="<button  id='show' 
class='buton'onclick='myFunction()'><b>HIDE</b></button>";
}
else
{
   document.getElementById('disp').innerHTML='';  
}
}

function myFunction() {
var x = document.getElementById("password");
if (x.type === "password") {
x.type = "text";
  document.getElementById("show").innerHTML='<b>HIDE</b>';
} else {
x.type = "password";
document.getElementById("show").innerHTML='<b>SHOW</b>';
}
}

需要在oninput.

中调用带括号()的显示函数

所以不要display,而是display()

就像你在评估 JS 代码。

display 会 return 函数,但不会被调用。

您需要在 oninput 上调用带括号的函数,例如 display()。没有括号,您实际上并没有调用函数,只是引用了函数。

function display(){
    var button=document.getElementById('password').value;
    var button2=document.getElementById('password');

    if(button.length>0 && button2.type==='password')
    {
        document.getElementById('disp').innerHTML="<button  id='button' class='buton'onclick='myFunction()'><b>SHOW</b></button>";

    }
    else if(button.length>0 && button2.type==='text')
    {
        document.getElementById('disp').innerHTML="<button  id='button' class='buton'onclick='myFunction()'><b>HIDE</b></button>";
    }
    else
    {
       document.getElementById('disp').innerHTML='';  
    }
}

function myFunction() {
    var x = document.getElementById("password");
    if (x.type === "password") {
        x.type = "text";
      document.getElementById("button").innerHTML='<b>HIDE</b>';
    } else {
        x.type = "password";
        document.getElementById("button").innerHTML='<b>SHOW</b>';
    }
}
<input type="password" id="password" oninput="display()" placeholder="Password">
<div id='disp'></div>