这是我目前正在做的事情:
<script>
function Answered(str) {
var script = document.getElementsByClassName('Answered')[str];
if(script!==null) {script.setAttribute("style", "");}
}
</script>
<span class=Answered style="background-color: #FFBED1">Is the sky blue?</span><br>
<select name="SkyBlue" onchange="Answered(0)">
<option value="">Please Select</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select><br>
<br>
<span class=Answered style="background-color: #FFBED1">How old are you?</span><br>
<input name=Age onchange="Answered(1)"><br>
<br>
<span class=Answered style="background-color: #FFBED1">Is grass green?</span><br>
<select name="GrassGreen" onchange="Answered(2)">
<option value="">Please Select</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select><br>
我想将“ Answered(0)”,“ Answered(1)”,“ Answered(2)”替换为“ Answered(classes =='Answered'在此元素之前)”之类的内容,以使元素可以移动或插入,不必重新编号。
最佳答案
更新!
如我所见,评论意识到先前的答案存在一些错误。因此,此处已进行了更新以在DOM树中查找实际元素。
而是传递this
:
function Answered(el) {
var isSpan = el.previousElementSibling;
var elem = checkPrev(el);
if (el.value === "") {
return false;
}
if (isSpan.nodeName === "SPAN") {
isSpan.setAttribute("style", "");
}
function checkPrev(currElem) {
if (currElem.previousElementSibling.nodeName !== 'SPAN') {
Answered(currElem.previousElementSibling)
} else {
return currElem.previousElementSibling;
}
}
}
<span class=Answered style="background-color: #FFBED1">Is the sky blue?</span>
<br>
<select name="SkyBlue" onchange="Answered(this)">
<option value="">Please Select</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br>
<br>
<span class=Answered style="background-color: #FFBED1">How old are you?</span>
<br>
<input name=Age onchange="Answered(this)">
<br>
<br>
<span class=Answered style="background-color: #FFBED1">Is grass green?</span>
<br>
<select name="GrassGreen" onchange="Answered(this)">
<option value="">Please Select</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br>
Fiddle