qre*_*0ct 1 html javascript css html5
当我选择一个单选按钮时,我希望某个"div"可见,并且当我选择另一个单选按钮时,我希望隐藏相同的div.我怎样才能做到这一点.以下是我的尝试.请告诉我这里有什么问题.
<label>For State govt. Ex- Employee
<span class="small">Select if you are a state govt. ex-employee</span>
</label>
<p>
<label>Yes</label>
<input type="radio" name="stateGov" id="stategov" value="yes" class="choice" onClick="stateGovOptions()"/>
<label>No</label>
<input type="radio" name="stateGov" id="stategov" value="no" class="choice" onClick="stateGovOptions()"/>
</p>
<!-- State govt. ex- employees -->
<div id="stateOptions" style="visibility:hidden">
<label>
<span class="small">Select </span>
</label>
<p>
<select title="stateGovExEmp" name="stateGovExEmp" id="fdivision">
<option value="state_gov_lev_not_sel">--Select Level At Which Worked At State --</option>
<option value="less">Less than or equal to one year</option>
<option value="between">More then one but less than two years</option>
<option value="more">More than two years</option>
</select>
</p>
</div>
Run Code Online (Sandbox Code Playgroud)
当选择"是"单选按钮时,应该可以看到id为"stateoptions"的div,当按下"no"单选按钮时,它应该再次隐藏.为了实现这一目标,我的尝试是js.
/* displays the contents when state gov ex-employee selected and removes it when not selected */
function stateGovOptions()
{
if(document.getElementById('stategov').value == 'yes')
document.getElementById('stateOptions').setAttribute('style','visibility:visible');
else
document.getElementById('stateOptions').setAttribute('style','visibility:hidden');
}
Run Code Online (Sandbox Code Playgroud)
按yes按钮显示所需的div,但是按下no按钮也会使其可见,尽管js函数中有'else'块.
请解释我在这里错过了什么.
nnn*_*nnn 10
您的html无效,因为您在多个元素上使用了相同的ID.这反过来意味着尝试选择那些元素并没有多大意义document.getElementById(),因为该方法返回单个元素(或null) - 那么它如何知道你指的是哪个元素?
对现有代码进行最小程度的更改以使其工作的方法是将单击项的值传递给您的函数:
<input type="radio" name="stateGov" value="yes" class="choice"
onClick="stateGovOptions(this.value)"/>
<label>No</label>
<input type="radio" name="stateGov" value="no" class="choice"
onClick="stateGovOptions(this.value)"/>
Run Code Online (Sandbox Code Playgroud)
...然后像这样使用它:
function stateGovOptions(val)
{
if(val == 'yes')
document.getElementById('stateOptions').setAttribute('style','visibility:visible');
else
document.getElementById('stateOptions').setAttribute('style','visibility:hidden');
}
Run Code Online (Sandbox Code Playgroud)
请注意,通常不会覆盖整个style属性来设置一个属性,只会设置有问题的属性:
document.getElementById('stateOptions').style.visibility = 'visible';
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/ryxCM/1/
| 归档时间: |
|
| 查看次数: |
40889 次 |
| 最近记录: |