这里怎么了?

问题描述 投票:-2回答:2

作为练习,我构建了一个不带任何html的显示和隐藏密码应用程序,只是html,head,body元素以及脚本元素,但是这里有错误:

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);

它只是给我密码字段和按钮,当我单击按钮时什么也没有发生。

我认为该函数有误,但我不知道在哪里...

javascript dom
2个回答
0
投票

我已尝试为您修复代码,现在您可以根据需要尝试它了,[[它将正常工作。我已经使用了[[click事件监听器,而不是将其设置为元素。并将setAttributeNodes替换为setAttribute

const inputOne = document.createElement('input'), attrOne = document.createAttribute('type'); inputOne.setAttribute('type', 'password'); 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); btnOne.addEventListener('click', function(e){ e.preventDefault(); if (inputOne.type == 'password') { inputOne.type = 'text'; this.innerHTML = 'Hide Password'; } else { inputOne.type = 'password'; this.innerHTML = 'Show Password'; } });

0
投票

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);
© www.soinside.com 2019 - 2024. All rights reserved.