我认为问题是我正在编写 .innerHtml
并覆盖表单元素,是否正确,抱歉浪费您的时间。
我正在尝试切换包含某些表单元素的 div 的可见性。这个想法是,如果用户选择了选择框的特定值,则 onchange
事件处理程序将使包含这些表单元素的特定 div 消失。当他们选择任何其他选项时,该 div 将重新出现。
if(chosen_option != option_that_makes_id dissappear){
document.getElementById(id).style.visibility = 'hidden';
document.getElementById(id).innerHTML = 'the if statement is working';
}else if(chosen_option == option_that_makes_id dissappear){
document.getElementById(id).style.visibility = 'visible';
}
我遇到的问题是 div 会正确消失,但是当我从检查列表中选择另一个值时,div 会重新出现,但不再包含表单值。
我将 .innerHTML
放入 if 语句中,然后当满足该条件时,我只看到 if 语句正在运行的文本,但看不到表单元素。
这是 JavaScript 的功能还是我做错了什么?
这是完整的未经编辑的 JavaScript 函数:
function change_div_visibility(id,select_id,div){//id is the id of the select box and the name of the div which you want to change the visibility of .
var select_option = document.getElementById(select_id).options;
var chosen_option = select_option[select_option.selectedIndex].value;
if(chosen_option != id){
document.getElementById(div).style.display = 'block';
document.getElementById(div).innerHTML = 'the if statement is working';
}else if(chosen_option == id){
document.getElementById(div).style.display = 'none';
document.getElementById(div).innerHTML = 'the else statement is working but for some reason the visibility of the div is not changing. ';
}
}
以及我试图操作的表单部分:
<p><label for='buying_options'>Select Buying Option</label><select onchange=\"change_div_visibility('new_buying_1','buying_options1','div1')\" id='buying_options1' name='buying_options1'><option value='undefined'>Select Buying Option</option>
<option value='new_buying_1'>New Buying Option</option>";
$y = '';
foreach($buying_options_arr as $key=>$value){
$x.= "<option value='$key' >$value</option>";
$y.= '<option value='.$key.'>'.$value.'</option>';
}
$x.= "</select> or</p> ";
$x.= "<div id='div1' >
<p><label for='add_new_buying_option'>Add new Buying Option: </label><input id='add_new_buying_option' type='text' name='add_new_buying_option1' /></p>\n";
$x.= "<p><label for='compression' >New Unit Quantity: </label><input type='text' id='compression' name='unit_quantity1' /></p>\n
";
最佳答案
您是否尝试过将 style.display 更改为“none”或“block”?
关于javascript - 使用 JavaScript 切换 div 的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1837946/