我是 JavaScript 和 JQuery 的新手,我遇到了以下问题。
在一个页面中,我有以下选择下拉列表:
<select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}" required="required" style="width: 55%;" onChange="nascondiBoxDocumentazione(this);">
......................................................................
......................................................................
OPTIONS LIST
......................................................................
......................................................................
</select>
然后我有这个 JavaScript 函数,当用户在上一个选择中选择一个选项时执行:
function nascondiBoxDocumentazione() {
alert("NASCONDI");
elementoDaNascondere = $("#docDelega");
selectedItem = $("#selTipoRap option:selected").text();
alert(selectedItem);
if(selectedItem == "Commissario Prefettizio" || selectedItem == "Delegato del presidente di provincia" || selectedItem == "Presidente di provincia" || selectedItem == "Sindaco") {
elementoDaNascondere.css("display: none;");
}
}
如您所见,此函数检索所选选项的文本值的值(它工作正常),如果文本是提供的值之一,则必须在 DOM 中隐藏一个 div(id= "docDelega") 通过这一行:**elementoDaNascondere.css("display: none;");
但是不行,这个div还是出现了。使用 FireBug 调试器,我可以看到 elementoDaNascondere 已正确初始化并包含选定的 div。
为什么?我错过了什么?我该如何解决这个问题?
最佳答案
代替 elementoDaNascondere.css("display: none;");
使用 .hide
或 .css('display', 'none');
function nascondiBoxDocumentazione() {
var elementoDaNascondere = $("#docDelega");
var selectedItem = $("#selTipoRap option:selected").text();
if (selectedItem == "Commissario Prefettizio" || selectedItem == "Delegato del presidente di provincia" || selectedItem == "Presidente di provincia" || selectedItem == "Sindaco") {
// elementoDaNascondere.hide();
elementoDaNascondere.css('display', 'none');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}" required="required" style="width: 55%;" onChange="nascondiBoxDocumentazione(this);">
<option>1</option>
<option>Commissario Prefettizio</option>
<option>3</option>
</select>
<div id="docDelega">DIV</div>
关于javascript - 为什么我不能使用 JavaScript 隐藏这个 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32995446/