jQuery starts with selector
Here's my code:
<script type="text/javascript">
$(document).ready(function () {
$("[class^=\"hide\"]").hide();
});
</script>
<div class="hide1">H开发者_如何学运维ide</div>
<div class="show1">Show</div>
<div class="hide2">Hide</div>
<div class="show2">Show</div>
<div class="hide3">Hide</div>
<div class="show3">Show</div>
<div class="hide4">Hide</div>
<div class="show4">Show</div>
But on page load, the hide
divs are still visible... what am I doing wrong?
Wow... I feel so stupid. I spent so much time banging my head against a wall, and only discover the solution after I post here...
So turns out I was doing everything correctly, but the div
s were in a View (I'm using MVC3) that was being loaded after $(document).ready
was being called. Moving the code into the View solved the problem.
Why do you have separate classes for those? Why not have a single hide class and set those attributes above (e.g. "hide1"
) as ids, then your selector can simply be on that class e.g. $('div.hide')
?
See http://jsfiddle.net/2GzpA/1/ for an example.
EDIT:
For your question, you comment:
@Tomgrohl well my code is actually much more complicated. I need to be able to hide and show each div individually.
Why not add a separate class to use for this case? Then your selector becomes $('div.specificCaseHideClass')
. You can have as many classes as you like and this is a fine example of when to add one.
try this its simple
$("div:even").hide();
Are you sure that jquery is included? This seems to work: http://jsfiddle.net/6ycbT/
Also, check your js console to see if any errors are getting thrown that might prevent this code from executing
switch out the outer quotes by single quotes and it works:
working fiddle: http://jsfiddle.net/geertvdc/hv4Ls/
code:
$('[class^="hide"]').hide();
You can do :
$(document).ready(function () {
$("div[class*=hide]").hide();
});
精彩评论