问题
I'am new to jquery and maybe this is a stupid question but I have searched for an answer just about everywhere without finding one. So, here we go:
I want to show different content depending on what option I select in a drop down form. As I have learnt here on StackOverflow, you ca use the change function to do this:
Example:
<script type="text/javascript">
$(document).ready(function() {
$('#myselector').change(function(){
$('.statecontent').hide();
$('#' + $(this).val()).show();
});
});
</script>
<select id="myselector">
<option value="state1"></option><br />
<option value="state2"></option><br />
<option value="state3"></option><br />
</select>
<div id="state1" class="statecontent">State1 Specific Page Content Goes here</div><br />
<div id="state2" class="statecontent">State2 Specific Page Content Goes here</div><br />
<div id="state3" class="statecontent">State3 Specific Page Content Goes here</div><br />
This code will alove me to show content thats inside the different divs depending on what 'state' I choose in the drop down. But how do I connect the values of the drop down to a specific class instead of an id. The problem is of course that I want to show several divs that share a common class when i select a state in the drop down.
I would very much appreciate if anyone could point me in the right direction.
Paul
回答1:
you can use class instead of Id like this
<div class="statecontent state1">State1 Specific Page Content Goes here</div><br />
<div class="statecontent state1">State1 Specific Page2 Content Goes here</div><br />
<div class="statecontent state2">State2 Specific Page Content Goes here</div><br />
<div class="statecontent state3">State3 Specific Page Content Goes here</div><br />
and your JQuery
$(document).ready(function() {
$('#myselector').change(function() {
$('.statecontent').hide();
$('.' + $(this).val()).show();
});
});
回答2:
$('.classname')
selects a class, so -
$('.' + $(this).val()).show();
would work if the value in your drop down corresponded to a class name.
回答3:
Read a jQuery doc about selectors. $("#someId")
selects the element havig someId
as id. $(".someClass")
selects the elements having someClass
as class. It uses the CSS3 notation. That's the heart of jQuery.
回答4:
$(document).ready(function () {
$(".col-md-12").load(function () {
$("module").removeClass("hidden");
});
来源:https://stackoverflow.com/questions/7865964/show-hide-content-with-specific-class-using-jquery