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);
添加回答
舉報