我向用户提出了一系列问题。根据用户的回答,他/她将看到另一个问题或一些文本。例如,这是我的代码(简体):
function layerOne() {
var radioNo = document.getElementById("radno");
var radioYes = document.getElementById("radyes");
var text = document.getElementById("layer-one-yes");
// Display 2nd question
if (radioNo.checked == true) {
radioYes.disabled = true;
}
// Deny access
if (radioYes.checked == true) {
radioNo.disabled = true;
text.style.display = "block";
}
}
#layer-one-yes {
display: none;
}
<!-- First question -->
<div id="layer-one">
<p>Are you under 18?</p>
<input type="radio" id="radno" onclick="layerOne()"><label for="radno">No</label>
<input type="radio" id="radyes" onclick="layerOne()"><label for="radyes">Yes</label>
<!-- Display this if user answers YES -->
<p id="layer-one-yes">Unfortunately, you cannot get access to desired files!</p>
</div>
希望您能明白。但是我的网站上有很多这样的功能。我想知道这是否是正确的方法。还是有更有效和正确的方法呢?
答案 0 :(得分:1)
我将创建一个接受目标元素ID和当前用户响应的函数。该功能将检查条件并显示或隐藏目标元素。 如果要保留用户响应,则可以将每个响应保存在数组或对象中。
更新
function checkAndShowNext(val, target) {
var text = document.getElementById(target);
// Display target question
// Deny access
}
<form name="myForm">
<input type="radio" name="myRadios" value="1" onclick="checkAndShowNext(this.value, 'nextQuestionId')" />
<input type="radio" name="myRadios" value="0" onclick="checkAndShowNext(this.value, 'nextQuestionId')" />
</form>
答案 1 :(得分:1)
当前以您的方法为基础,只需重复一次即可,但对于包含下一个问题的Div而言。就效率而言,显然还有许多其他方法可以执行此操作,但这取决于解释和经验。如果您现在最熟悉此技术,请先完成它,然后再尝试其他一些技术,并对此有所了解。
您可以创建单独的函数,这些函数也将根据用户的响应使用户前进,而不是“注入”到display属性,您可以创建两个标题分别为hide
和show
的类,并根据响应替换相应容器的类。通常,这就是我通常自己获得这些结果的方式,但是这都是我的偏爱。
以下是代码笔:https://codepen.io/codespent/pen/bKXdGb
function layerOne() {
var radioNo = document.getElementById("radno");
var radioYes = document.getElementById("radyes");
var text = document.getElementById("layer-one-yes");
var element = document.getElementById("layer-two");
// Display 2nd question
if (radioNo.checked == true) {
radioYes.disabled = true;
element.style.display = "block";
}
// Deny access
if (radioYes.checked == true) {
radioNo.disabled = true;
text.style.display = "block";
}
}
#layer-one-yes {
display: none;
}
#layer-two {
display: none;
}
.show {
display: block;
}
<!-- First question -->
<div id="layer-one">
<p>Are you under 18?</p>
<input type="radio" id="radno" onclick="layerOne()"><label for="radno">No</label>
<input type="radio" id="radyes" onclick="layerOne()"><label for="radyes">Yes</label>
<!-- Display this if user answers YES -->
<p id="layer-one-yes">Unfortunately, you cannot get access to desired files!</p>
</div>
<div id="layer-two">
<p>Are you under 21?</p>
<input type="radio" id="radno" onclick="layerOne()"><label for="radno">No</label>
<input type="radio" id="radyes" onclick="layerOne()"><label for="radyes">Yes</label>
</div>