动态登录表单格式化问题:如何修正Username标签首字母大写显示
解决登录表单标签首字母大写问题
嘿,其实你遇到的问题和元素追加到表单的方式完全无关——问题出在标签文本的大小写设置上!你期望显示首字母大写的"Username",但当前代码里肯定是把标签文本写成了小写的"username",所以才会出现不符合预期的显示结果。
先结合你给出的代码片段,还原一下你大概率的实现逻辑(补全了缺失的部分):
function addLogin(){ var f = document.createElement("form"); f.setAttribute('method', "post"); f.setAttribute('action', "project/login"); // 这里是问题所在:标签文本用了小写的username var usernameLabel = document.createElement("label"); usernameLabel.textContent = "username:"; var usernameInput = document.createElement("input"); usernameInput.type = "text"; usernameInput.name = "username"; var passwordLabel = document.createElement("label"); passwordLabel.textContent = "password:"; var passwordInput = document.createElement("input"); passwordInput.type = "password"; passwordInput.name = "password"; var repeatPwdLabel = document.createElement("label"); repeatPwdLabel.textContent = "repeat password:"; var repeatPwdInput = document.createElement("input"); repeatPwdInput.type = "password"; repeatPwdInput.name = "repeatPassword"; // 追加元素到表单 f.appendChild(usernameLabel); f.appendChild(usernameInput); f.appendChild(document.createElement("br")); f.appendChild(passwordLabel); f.appendChild(passwordInput); f.appendChild(document.createElement("br")); f.appendChild(repeatPwdLabel); f.appendChild(repeatPwdInput); document.body.appendChild(f); }
只需要把用户名标签的文本改成首字母大写的"Username:",就能解决问题:
var usernameLabel = document.createElement("label"); usernameLabel.textContent = "Username:"; // 这里改成大写U即可
如果你的代码是用innerHTML设置标签内容,同样只需要调整文本的大小写就行,和元素追加的顺序、方式没有关系。
另外,给个小建议:为了让表单结构更语义化,你可以把每个标签+输入框的组合用<div>包裹起来,后续调整样式会更方便:
// 用户名分组 var usernameGroup = document.createElement("div"); usernameGroup.appendChild(usernameLabel); usernameGroup.appendChild(usernameInput); f.appendChild(usernameGroup); // 密码分组 var passwordGroup = document.createElement("div"); passwordGroup.appendChild(passwordLabel); passwordGroup.appendChild(passwordInput); f.appendChild(passwordGroup); // 重复密码分组 var repeatPwdGroup = document.createElement("div"); repeatPwdGroup.appendChild(repeatPwdLabel); repeatPwdGroup.appendChild(repeatPwdInput); f.appendChild(repeatPwdGroup);
内容的提问来源于stack exchange,提问作者Zack Maguffin
相关产品推荐
相关产品推荐

