开发者

Refactoring basic javascript

I have the following code:

<script type="text/javascript"&开发者_开发百科gt;  
$(function() {
    //div1 toggle
    function runEffect(){
        var options = {};
        //run the effect
        $("#div1_toggle").toggle("blind",options,350);
    };
    $("#div1").click(function() {
        runEffect();
        return false;
    });
});
</script>

Imagine the above code literally duplicated for a number of divs named div1, div2, div3, etc.

This is horrendously bad, and I would like to rewrite the code such that it applies to a div of any name to toggle a div of (equal name + _toggle).

Bonus: how could I still allow some of these divs to incorporate a different toggle speed (i.e. the 350ms specified above) while reducing redundancy?


A lot of the time, simplifying your javascript is best done by simplifying your HTML first.

It would be best if you don't use IDs for the Divs (you don't want to have to keep increasing the ID number yourself do you?) but instead used classes (classes are generic and repeatable). This would work best if the "toggle div" is related to the "clicked div" somehow, for example, one is after the other. I would do it like this:

<div class="clickable">
</div>
<div class="togglable">
</div>
... rinse and repeat, as many times as you want...

Then your script is simple:

$(function () {
   $(".clickable").click(function () {
      $(this).next(".togglable").toggle("blind", {}, 350);
   });
});

As for some divs toggling at a different speed? Sure, just add another class:

<div class="clickable">
</div>
<div class="fast togglable">
</div>

Now change the script to:

$(function () {
   $(".clickable").click(function () {
      // A "normal" div
      $(this).next(".togglable:not(.fast)").toggle("blind", {}, 350);
      // A "fast" div
      $(this).next(".togglable.fast").toggle("blind", {}, 100); // New value
   });
});

There are other ways to do this. You can stick the "fast" class on the "clickable" div instead, then you'd have two different click handlers. You could have a "normal" and a "fast" class, so you don't have to do :not(.fast) and can just do .normal instead. Hope this gives you some ideas...


you can pass a comma separated list of selectors

$('#div1, #div2, #div3, .someClass')

and then check inside the handler what this refers to, and do something based on that.

you can even select all divs

$('div') ... though that is not a great idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜