Show / hide divs clarification with javascript
A highly similar question has been asked already, and it has partly solved my problem, but I'd like to know if class
or id
NAMES can be used in this example instead of ul li
- .menu
, #menu
, etc.
css: div { display:none; backgrou开发者_JS百科nd:red; width:200px; height:200px; }
js:
$(function() {
$('ul li').each(function() {
$(this).click(function(e) {
var i = $(this).index();
$('div').hide();
$('div:eq('+i+')').show();
});
});
});
Here's the jsfiddle for this example: http://jsfiddle.net/Z3Hj7/
Apologies in advance if this question is stupid, but I've been mucking about with it for a while and cant figure it out.
Yes, you can:
$(function() {
$('#menu .list').click(function(e) {
var i = $(this).index();
$('div').hide();
$('div:eq('+i+')').show();
});
});
There is no need at all for using a loop.
Here is a demo
To improve your js, you can use the arguments of the $.each
function:
$(function() {
$('ul li').each(function(i, e) {
$(e).click(function() {
$('div').hide();
$('div:eq('+i+')').show();
});
});
});
I wrote this snippet some time ago to hide anything with an id. The elements img, div, a, li ul, table etc: all need to have style set to visible/relative visibility: visible; position: relative;
The function changes visible to hidden to hide the element then sets the position to absolute to keep the element from creating a white space in its position.
Fiddled http://jsfiddle.net/ShawnsSpace/URRDy/
<div id="togglethis" style="visibility: visible; position: relative; border: 4px dotted;">Click the button to toggle this Div</div>
<button onclick="toggle('togglethis');">Toggle</button>
<script type="text/javascript">
//<![CDATA[
function toggle(obj) {
var item = document.getElementById(obj);
if (item.style.visibility=='visible') {
item.style.visibility = 'hidden';
}
else {
item.style.visibility = 'visible';
}
//
if (item.style.position=='relative') {
item.style.position = 'absolute';
}
else {
item.style.position = 'relative';
}
}
//]]>
</script>
In answer to the question about using the ID and class as the selector, yes you can: http://jsfiddle.net/Z3Hj7/1/
精彩评论