开发者

jQuery shortcuts / technique for toggling classes

开发者 https://www.devze.com 2023-01-21 20:07 出处:网络
In jQuery, is there another way to write this? Version 1 $(\"#date_filter-enable\").click(function() {

In jQuery, is there another way to write this?

Version 1

     $("#date_filter-enable").click(function() {

        $("#search_dates").removeClass("hidden");
     });

     $("#date_filter-disable").click(function() {

        $("#search_dates").addClass("hidden");
     });

Version 2

     $("input[id^=date_filter-]").click(funct开发者_JS百科ion(e) {

        var clicked = $(e.target);
        var id = clicked.attr("id").split("-");
        var action = id[1];

        if(action == "enable")  
         $("#search_dates").removeClass("hidden");
        else
         $("#search_dates").addClass("hidden");
     });

I'm used to coding like this...but I want to know if there are much effective, readable, cool way of writing it...like toggling, chaining...best practices I don't know ^^

I appreciate you sharing it! ^^


You should use the toggleClass method.

$("input[id^=date_filter-]").click(function(e) {
     $("#search_dates").toggleClass("hidden");
 });


$("input[id^=date_filter-]").click(function(e) {
        if($(this).attr("id").split("-")[1] == "enable")  
         $("#search_dates").removeClass("hidden");
        else
         $("#search_dates").addClass("hidden");
     });
0

精彩评论

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