首页 > 解决方案 > 这里有什么问题?

问题描述

我构建了一个显示和隐藏密码应用程序,没有任何 html,只有 html、head、body 元素,当然还有 script 元素作为一种练习,但这里有错误:

const inputOne = document.createElement('input');
const attrOne = document.createAttribute('type');
attrOne.value = 'password';
inputOne.setAttributeNode(attrOne);

const btnOne = document.createElement('button');
btnOne.innerHTML = 'Show Password';
document.body.appendChild(inputOne);

const BRBetween = document.createElement('br');
const BRsBetween = document.createElement('br');
document.body.appendChild(BRBetween);
document.body.appendChild(BRsBetween);
document.body.appendChild(btnOne);

const shHiPassword = function shHiPass() {
  if (inputOne.type == 'password') {
    inputOne.type = 'text';
    inputTwo.innerHtml = 'Hide Password';
  } else {
    inputOne.type = 'password'

    inputTwo.innerHtml = 'Show Password';
  }
};

const attrTwo = document.createAttribute('onclick');
attrTwo.value = shHiPassword;
btnOne.setAttributeNode(attrTwo);

它只是给我密码字段和按钮,当我点击按钮时没有任何事情发生。

我认为功能错误,但我不知道在哪里......

标签: javascriptdom

解决方案


尝试将您的onclick属性设置为字符串值。这是一个工作示例:

const inputOne = document.createElement('input');
const attrOne = document.createAttribute('type');
attrOne.value = 'password';
inputOne.setAttributeNode(attrOne);

const btnOne = document.createElement('button');
btnOne.innerHTML = 'Show Password';
document.body.appendChild(inputOne);

const BRBetween = document.createElement('br');
const BRsBetween = document.createElement('br');
document.body.appendChild(BRBetween);
document.body.appendChild(BRsBetween);
document.body.appendChild(btnOne);

function shHiPassword() {
  if (inputOne.type == 'password') {
    inputOne.type = 'text';
    btnOne.innerHTML = 'Hide Password';
  } else {
    inputOne.type = 'password'
    btnOne.innerHTML = 'Show Password';
  }
};

const attrTwo = document.createAttribute('onclick');
attrTwo.value = 'shHiPassword()';
btnOne.setAttributeNode(attrTwo);


推荐阅读