Hello stackoverflow社区,
我试图通过if语句和其他变量创建变量,但它不起作用。如果有人能帮助我,我会非常感激。
这是我创建returntouser变量的代码
function userinput() {
return returntouser = metaTitle + "\n" + metaDescription + "\n" + metaKeywords;
}
现在我试图从" metaTitle"中创建一个if函数。变量。如果用户不在文本表单中写任何内容,那么" metaTitle"变量不会被添加到" returntouser"变量
function userinput() {
return returntouser = if (document.getElementById("userinputTitle").length > 0) { return metaTitle } + "\n" + metaDescription + "\n" + metaKeywords;
}
有人可以告诉我如何添加这个函数来添加" metaTitle"改变为" returntouser"变量与否
答案 0 :(得分:6)
您可以使用?
- 运算符执行条件内联。它也被称为三元运算符。更多信息here。
示例:
value = 10 > 3 ? "10 is bigger than 3" : "10 is smaller than 3";
答案 1 :(得分:1)
你必须分开执行。
function userinput() {
var returntouser = "";
if (document.getElementById("userinputTitle").length > 0) { returntouser += metaTitle }
return returntouser + "\n" + metaDescription + "\n" + metaKeywords;
}
答案 2 :(得分:1)
尝试拆分行动:
function userinput() {
var meta = metaDescription + "\n" + metaKeywords;
if (document.getElementById("userinputTitle").length == 0) return meta;
return metaTitle + "\n" + meta;
}
或用于学习目的:
function userinput() {
var meta = [metaDescription, metaKeywords];
if (document.getElementById("userinputTitle")) meta.unshift(metaTitle);
return meta.join('\n');
}
或更现代的浏览器
function userinput() {
var mt = document.getElementById('userinputTitle')? `${metaTitle}\n` : '';
return `${mt}${metaDescription}\n${metaKeywords}`;
}