I am discovering JQuery and can't find an answer to my question, after a lot of research, because I don't know how to express it well.
I have 2 rulers + 2 guides on my page and 2 buttons to show or hide them. I wrote something that works but I would like to optimize the code by making it shorter.
Here it is:
$('#ruler-bg1, #ruler-bg2').hide();
$('#ruler1').click(function() 开发者_高级运维{
$('#ruler-bg1').slideToggle(100);
$('#guide1').toggleClass('guide-on');
});
$('#ruler2').click(function() {
$('#ruler-bg2').slideToggle(100);
$('#guide2').toggleClass('guide-on');
});
What I can't figure out is how to group the 2 functions so a click on #ruler+number
shows #ruler-bg+same_number
and #guide+same_number
.
Something like this should do:
$('#ruler1, #ruler2').click(function(){
var num = this.id.substr(6);
$('#ruler-bg' + num).slideToggle(100);
$('#guide' + num).toggleClass('guide-on');
});
It would probably be nicer if there was some structural relationship between the element clicked and the elements acted upon...
I would add a class "ruler" to all the "rulers" and use the id´s as identifier on the ruler-bg and guide.
$('.ruler').click(function(){
$('#bg-'+this.id).slideToggle(100);
$('#guide-'+this.id).toggleClass('guide-on');
});
initRuler(1);
initRuler(2);
function initRuler(id) {
$('#ruler' + id).click(function() {
$('#ruler-bg' + id).slideToggle(100);
$('#guide' + id).toggleClass('guide-on');
});
}
精彩评论