gpt4 book ai didi

javascript - 根据参数替换占位符

转载 作者:行者123 更新时间:2023-12-02 22:00:54 25 4
gpt4 key购买 nike

我正在尝试使该函数根据所选语言将当前占位符替换为另一个占位符。我目前收到此错误:

Uncaught TypeError: Cannot read property 'fname' of undefined

如果我可以提供任何其他信息,请告诉我。

HTML 按钮

<input type="button" value="setInputs SI" onclick="setInputs('si')">
<input type="button" value="setInputs AN" onclick="setInputs('an')">
<input type="button" value="setInputs DE" onclick="setInputs('de')">
<input type="button" value="setInputs IT" onclick="setInputs('it')">
<input type="button" value="setInputs HR" onclick="setInputs('hr')">
<input type="button" value="setInputs RU" onclick="setInputs('ru')">

HTML 表单 - 占位符

<input type="text" name="fname" id="fname" required maxlength="50" minlength="1" placeholder="Janez" 
onfocus="this.placeholder = ''" onblur="this.placeholder = 'Janez'" /><br />
<input type="text" name="lname" id="lname" required maxlength="50" minlength="1" placeholder="Novak"
onfocus="this.placeholder = ''" onblur="this.placeholder = 'Novak'" /><br />
<input type="email" name="email" id="email" autofocus="autofocus" required placeholder="moj@email.com"
onfocus="this.placeholder = ''" onblur="this.placeholder = 'moj@email.com'" />

JS

let fname = document.getElementById("fname");   
let lname = document.getElementById("lname");
let email = document.getElementById("email");

const placeholders = {
sl: { fname: "Janez", lname: "Novak", email: "moj@email.si" },
en: { fname: "John", lname: "Doe", email: "my@email.us" },
de: { fname: "Kommissar", lname: "Rex", email: "mein@email.deu" },
it: { fname: "Julius", lname: "Cezar", email: "barilla@email.it"},
hr: { fname: "Mirko", lname: "Mirkic", email: "moj@email.hr"},
ru: { fname: "Joseph", lname: "Russian", email: "moji@email.ru"}
};

function setInputs(language) {
if (language) {
const values = placeholders[language];
fname.setAttribute("placeholder", values.fname);
lname.setAttribute("placeholder", values.lname);
email.setAttribute("placeholder", values.email);
}
}

编辑

我尝试对这个 JS 函数进行“逆向工程”。

const lngs = document.getElementsByClassName("lng");

function setLanguage() {
for (var i = 0; i < lngs.length; i++) {
if (lngs[i].className.includes(languageFistTwo)){
lngs[i].style.display = "inline";
} else {
lngs[i].style.display = "none";
}
}
}

最佳答案

如果我正确理解你想要实现的目标,你需要在占位符对象中搜索语言。您可以像这样检查对象的键:

Object.keys(placeholders).includes(language)

顺便说一句,您在代码中使用的 className 通常在 React 中使用,并且与元素的 CSS 类相关,与占位符对象无关...

检查以下代码笔以查看实时运行的代码:https://codepen.io/loic_baron/pen/povGZZw

关于javascript - 根据参数替换占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59881542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com