jQuery .each inside function
I dont know why .each() not working here in my code
function showhide(id){
$('#mydiv'+id).each(function(){
if(this).is(":visible") ) {
$(this).css('display','none');
}else {
$(this).css('display','block');
}
});
}
<span id="mydiv" style="display:none;">
blah blah blah
</span>
<a href="#" onclick="showhide($id);return false;" />show/开发者_开发知识库hide</a>
You are using an id selector - id's should be unique within the page, so calling .each with an id selector makes no sense.
Instead assign a class to each of the elements involved and use
$('.mydivclass').each( ... );
Looks like your 3rd line has some syntax problems. Here it is cleaned up;
...
if ( $(this).is(":visible") ) {
...
Like others have stated, ID's are supposed to be unique, so it doesn't make much sense to iterate over multiple elements with the same ID, use a class instead.
Also, a better way to structure your JavaScript is to attache your event handlers (onclick in your case) in one place and not inline in your html, this makes for cleaner code and is also easier to maintain.
Instead of accessing the css property directly i.e $('yourelement').css('display', 'none')
you can do $('yourelement').hide()
or $('yourelement').show()
;
So your JS now looks like the one below.
$(function(){
var my_divs = $('.mydiv');
$('#show_hide').click(function(){
my_divs.each(function(){
var $this = $(this);
if( $this.is(':visible') )
$this.hide();
else
$this.show();
});
});
});
In your HTML you now have.
<span class="mydiv">
blah blah blah
</span>
<a id="show_hide" href="#" />show/hide</a>
in your css file
.mydiv{
display: none;
}
function showhide(id){
$('#mydiv'+id).each(function(){
if($(this).is(":visible") ) {
$(this).css('display','none');
}else {
$(this).css('display','block');
}
});
}
This should be the final product
Try
function showhide(id){
$('#'+id).each(function(){
$this = $(this);
if($this.is(":visible") ) {
$this.css('display','none');
}else {
$this.css('display','block');
}
});
}
Or
function showhide(id){
$('#'+id).each(function(){
$this = $(this);
if($this.is(":visible") ) {
$this.hide();
}else {
$this.show();
}
});
}
<span id="mydiv" style="display:none;">
blah blah blah
</span>
<a href="#" onclick="showhide("mydiv");return false;" />show/hide</a>
While the underlying problem has been solved in the accepted answer, you might drastically simplify your code:
function showhide(classname){
$('.' + classname).toggle();
}
The explicit iteration with .each
is unnecessary, since most jQuery methods automatically iterate over all matched elements in the jQuery object. Moreover, the showing and hiding can be done with .toggle
.
精彩评论