2 回答
TA贡献1801条经验 获得超8个赞
我试图修复你的代码,现在你可以尝试一下,它会按你的意愿工作。我已经使用单击事件侦听器而不是将其设置为元素。并用setAttribute替换了setAttributeNodes
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';
}
});
TA贡献1802条经验 获得超4个赞
尝试将您的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);
添加回答
举报