这是怎么了

时间:2019-09-30 17:35:59

标签: javascript dom

作为练习,我构建了一个不带任何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);

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

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

2 个答案:

答案 0 :(得分:0)

尝试将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);

答案 1 :(得分: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';
 }
});