javascript - 这里有什么问题?
问题描述
我构建了一个显示和隐藏密码应用程序,没有任何 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);
它只是给我密码字段和按钮,当我点击按钮时没有任何事情发生。
我认为功能错误,但我不知道在哪里......
解决方案
尝试将您的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);
推荐阅读
- php - 用于过滤包含多维数组中搜索的值的 eval
- .net - If条件VB.net中的Linq Where语句
- julia - Julia - 定义一个二维数组,其中一个数组作为一维元素
- docker - docker-compose 日志记录不适用于 syslog 选项
- delphi - 如何将所有 *.txt 打开到列表框
- python - Python 函数中的 reStructuredText 未在 Robot Framework hub 中显示
- r - Forecast::ets, auto.arima 偏移 1
- python - 如何防止 python 服务器写入终端窗口?
- ios - 向 tableViewCell 添加一些标签。表数取决于服务器数据
- javascript - 如何“减少外部脚本的 JavaScript 执行时间”?