I have a javascript function that toggles the display for rows in a table. The dilemma is that I would like to display one row at a time. What is a neat way to do this?
function optionSelected() {
var optionSelect = document.getElementById('ddlSelect');
var strTest = optionSelect.options[optionSelect.selectedIndex].value;
var rowHeader = document.getElementById(strTest);
var row = document.getElementById(strTest);
if (rowHeader.style.display == '') {
rowHeader.style.display = 'none';
row.style.display = 'none';
}
else {
rowHeader.style.display = '';
row.style.display = '';
}
}
<select id="ddlSelect" onchange="optionSelected()">
开发者_开发知识库<option value="optionA">A</option>
<option value="optionB">B</option>
<option value="optionC">C</option>
<option value="optionD">D</option>
</select>
<table id="tableList">
<tr id="optionA"><td>DisplayA</td></tr>
<tr id="optionB"><td>DisplayB</td></tr>
<tr id="optionC"><td>DisplayC</td></tr>
<tr id="optionD"><td>DisplayD</td></tr>
</table>
simple with jquery
$('tr').hide();
$('#'+strTest).show();
This is your vanilla Javascript solution (although I'd rather go with jQuery):
function optionSelected() {
var sel = document.getElementById('ddlSelect');
for (var i=0; i<sel.options.length; i++) {
document.getElementById(sel.options[i].value)
.style.display = sel.options[i].selected ? '' : 'none';
}
}
Also, if you want to initialize your display, you should call optionSelected()
once in an onLoad handler.
Instead of looping on DOM nodes, you can change style rules and use the speed of the CSS selectors instead.
Here is an example to show one line at a time and stay.
If you want to remove them at each selection you can clear the style each time you make a selection.
<body>
<style id="styles">
table tr{
display:none;
}
</style>
<select id="ddlSelect" onchange="optionSelected()">
<option value="optionA">A</option>
<option value="optionB">B</option>
<option value="optionC">C</option>
<option value="optionD">D</option>
</select>
<table>
<tr id="optionA"><td>DisplayA</td></tr>
<tr id="optionB"><td>DisplayB</td></tr>
<tr id="optionC"><td>DisplayC</td></tr>
<tr id="optionD"><td>DisplayD</td></tr>
</table>
<script>
function optionSelected() {
var optionSelect = document.getElementById('ddlSelect'),
styles = document.getElementById('styles'),
selector = '#' + optionSelect.options[optionSelect.selectedIndex].value,
rule = 'display:block';
if(styles.styleSheet){
styles.styleSheet.cssText = selector + '{' + rule + '}';
}else{
styles.appendChild(document.createTextNode(selector + '{' + rule + '}'));
}
}
</script>
</body>
精彩评论