How to reduce my repeated jQuery code
first post here at this great website!
I would like to reduce the amount of code for the following, espacially as there are more parts I need to add in the future - I'm sure there must be an easy way but I'm just not seeing it. Thanks for your help!
$(document).ready(function(){
$(function(){
$('#iqdrive').click(
function(){
$('#iqdrive-cont').show();
});
});
$(function(){
$('#optiwave').click(
function(){
$('#optiwave-cont').show();
});
});
$(function(){
$('#vario').click(
function(){
$('#vario-cont').show();
});
});
$(function(){
$('#autostain').click(
function(){
开发者_StackOverflow中文版 $('#autostain-cont').show();
});
});
$(function(){
$('#autoload').click(
function(){
$('#autoload-cont').show();
});
});
});
Firstly, you don't need to nest document.ready
functions (all the $(function() {
are redundant as it is equivalent to document.ready
). And to simplify your code:
$(function() {
$('#iqdrive, #optiwave, #vario, #autostain, #autoload').click(function() {
$('#' + this.id + '-cont').show();
});
});
All of the internal $(function())
calls are unnecessary, since $(function())
is an alias for $(document).ready(function())
. Your example shows a lot of repetition of the same sort of task; that's very easy to consolidate.
$(document).ready(function(){
$('#iqdrive, #optiwave, #vario, #autostain, #autoload').click(function(){
$($(this).attr("id") + "-cont").show();
});
});
What that does is register for clicks on elements with any of those IDs, and on click, gets the ID of the clicked element, appends -cont
, and uses that as a selector to get a set of elements to show.
精彩评论