我正在尝试根据用户选择显示一些按钮和消息,现在只有“正确”显示无论选择,我的代码有什么问题?:
HTML:
var shareMessage=
new
{
content =
new
{
title ="",
submitted_url = "http://www.example.com",
submitted_image_url = "http://www.example.com/images/someimage.jpg",
description = ""
},
//comment = "Comment:" + LINKEDIN.POST_CONTENT,
visibility = new { code = LINKEDIN.VISIBILITY }
};
使用Javascript:
<button id = "dec12" onclick="clickF1()"> December 12 <br> 2014 </button>
<button id = "nov13" onclick="clickF1()"> November 13 <br> 2014 </button>
<button id = "dec15" onclick="clickF1()"> December 15 <br> 2014 </button>
<h2 id ="output1"></h2>
答案 0 :(得分:2)
您的if
语句始终为true,因为文字字符串始终存在。 (它在JavaScript中始终是“真实的”。)即使你删除引号并只检查变量,它们仍然总是是真的,因为这些变量总是存在。
听起来你只想知道点击了哪个元素。让元素将标识符传递给函数。像这样:
<button id = "dec12" onclick="clickF1('dec12')"> December 12 <br> 2014 </button>
<button id = "nov13" onclick="clickF1('nov13')"> November 13 <br> 2014 </button>
<button id = "dec15" onclick="clickF1('dec15')"> December 15 <br> 2014 </button>
然后在函数中检查该值:
function clickF1(day) {
if (day == "dec12") {
document.getElementById("output1").innerHTML = "Correct!";
} else if (day == "nov13") {
document.getElementById("output1").innerHTML = "Way off!";
} else if (day == "dec15") {
document.getElementById("output1").innerHTML = "Close but nope!";
}
}
答案 1 :(得分:1)
您的clickF1
函数始终运行相同的代码。您应该在单击时传递一些变量来分隔按钮。
例如,您可以传递按钮,然后分析它的ID,如下所示:
<强> HTML:强>
<button id = "dec12" onclick="clickF1(this)"> December 12 <br> 2014 </button>
<button id = "nov13" onclick="clickF1(this)"> November 13 <br> 2014 </button>
<button id = "dec15" onclick="clickF1(this)"> December 15 <br> 2014 </button>
<强>使用Javascript:强>
function clickF1(button) {
var id = button.id;
if (id == "dec12") {
document.getElementById("output1").innerHTML = "Correct!";
} else if (id == "nov13") {
document.getElementById("output1").innerHTML = "Way off!";
} else if (id == "dec15") {
document.getElementById("output1").innerHTML = "Close but nope!";
}
}