我在一段需要多行“if”逻辑来处理功能的代码方面遇到了一些麻烦。
其中两个 if 语句执行相同的操作,在我看来,它们是相互抵消的。
function visibleCheck() {
var target = document.getElementById('contentType').val();
if (target != "BYOC - Document to Exam") {
document.getElementById('VideoMinutes').style.display = 'block';
}
else document.getElementById('VideoMinutes').style.display = 'none';
if ((target != "Custom Production - Avatar") {
document.getElementById('Questions').style.display = 'block';
}
else document.getElementById('Questions').style.display = 'none';
if ((target != "Custom Production - Video") {
document.getElementById('Questions').style.display = 'block';
}
else document.getElementById('Questions').style.display = 'none';
}
第一个 if 语句运行良好。第二个似乎根本没有运行。第三个运行良好。
如果我重新排序第二个和第三个交换位置,新的第二个将不起作用。
如果我使用或运算符“||”并结合它根本不起作用的语句。
无论 if 语句的条件如何,第三条语句始终有效。
如果我制作第二个和第三个 if 或语句,则两者都不起作用。
有什么想法吗?
我正在 salesforce 内的 Visualforce 页面上使用它(如果这有什么不同的话)。
最佳答案
首先,请注意 DOMElements 没有 val()
方法,该方法仅适用于 jQuery 对象。您应该使用 value
属性。
其次,逻辑存在缺陷,因为 Questions
元素的执行可能会经历多个相互矛盾的条件。试试这个:
function visibleCheck() {
var target = document.getElementById('contentType').value;
if (target != "BYOC - Document to Exam") {
document.getElementById('VideoMinutes').style.display = 'block';
}
else {
document.getElementById('VideoMinutes').style.display = 'none';
}
if (target != "Custom Production - Avatar" && target != "Custom Production - Video") {
document.getElementById('Questions').style.display = 'block';
}
else {
document.getElementById('Questions').style.display = 'none';
}
}
由于您已使用 jQuery 对其进行了标记,因此这是一个简化的 jQuery 版本:
function visibleCheck() {
var target = $('#contentType').val();
$('#VideoMinutes').toggle(target != 'BYOC - Document to Exam');
$('#Questions').toggle(target != "Custom Production - Avatar" && target != "Custom Production - Video");
}
关于javascript - 多个 If 语句相互抵消? (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325885/