如何缩短这个过长的JavaScript函数?

时间:2012-08-02 16:58:50

标签: javascript

我有一个简单的脚本,它选择一个类并添加一个选定的类,并将其从具有相似类的所有其他类中删除。这一切都很完美,但我知道必须有一个更好的方法来解决这个问题,我只是无法解决这个问题。它是否涉及到这样的事情?

$('.adv-option-set a, .adv-option-set2 a, .adv-option-set3 a, .adv-option-set4 a, .adv-option-set5 a, .adv-option-set6 a, .adv-option-set7 a').click(function()
{
    // if clicked item is selected then do nothing
    if ($(this).hasClass('selected')){}

    // otherwise deselect all and select just this one
    else
    {
        $('.adv-option-set a').removeClass('selected');
        $(this).addClass('selected');
    }

    {
        $('.adv-option-set2 a').removeClass('selected');
        $(this).addClass('selected');
    }

    {
        $('.adv-option-set3 a').removeClass('selected');
        $(this).addClass('selected');
    }
});

所以这是我目前拥有并正在运行的代码:

$('.adv-option-set a').click(function()
{
    // if clicked item is selected then do nothing
    if ($(this).hasClass('selected')){}

    // otherwise deselect all and select just this one
    else
    {
        $('.adv-option-set a').removeClass('selected');
        $(this).addClass('selected');
    }
});

$('.adv-option-set2 a').click(function()
{
    // if clicked item is selected then do nothing
    if ($(this).hasClass('selected')){}

    // otherwise deselect all and select just this one
    else
    {
        $('.adv-option-set2 a').removeClass('selected');
        $(this).addClass('selected');
    }
});

$('.adv-option-set3 a').click(function()
{
    // if clicked item is selected then do nothing
    if ($(this).hasClass('selected')){}

    // otherwise deselect all and select just this one
    else
    {
        $('.adv-option-set3 a').removeClass('selected');
        $(this).addClass('selected');
    }
});

等。直到' .adv-option-set7 a'

编辑以显示DOM:

      <article id="filter">
        <ul id="filter-nav" class="option-set">
          <li>Filter: </li>
          <li><a data-categories="*" data-subid="all" class="selected">All</a></li>
          <li><a data-categories="tubs-and-showers" data-subid="tubs-and-showers">Tubs &amp; Showers</a></li>
          <li><a data-categories="countertops" data-subid="countertops">Countertops</a></li>
          <li><a data-categories="faucets" data-subid="faucets"><s>Faucets</s></a></li>
          <li><a data-categories="cabinetry" data-subid="cabinetry"><s>Cabinetry</s></a></li>
          <li><a data-categories="flooring" data-subid="flooring"><s>Flooring</s></a></li>
          <li><a data-categories="toilets" data-subid="toilets"><s>Toilets</s></a></li>
          <li><a data-categories="accessories" data-subid="accessories"><s>Accessories</s></a></li>
        </ul>
        <div id="advfilter" class="advfilter filter-nav hidden">
          <ul id="tubs-and-showers" class="adv-option-set1">
            <li><span class="small">ADV</span> Filter: </li>
            <li><a data-categories="modular">Modular</a></li>
            <li><a data-categories="custom">Custom</a></li>
          </ul>
          <ul id="countertops" class="adv-option-set2">
            <li><span class="small">ADV</span> Filter: </li>
            <li><a data-categories="marble">Marble</a></li>
            <li><a data-categories="solid-surface">Solid Surface</a></li>
            <li><a data-categories="laminate"><s>Laminate</s></a></li>
            <li><a data-categories="granite"><s>Granite</s></a></li>
          </ul>
          <ul id="faucets" class="adv-option-set3">
            <li><span class="small">ADV</span> Filter: </li>
            <li><a data-categories="">Coming Soon</a></li>
            <li><a data-categories="">Coming Soon</a></li>
          </ul>
          <ul id="cabinetry" class="adv-option-set4">
            <li><span class="small">ADV</span> Filter: </li>
            <li><a data-categories="">Coming Soon</a></li>
            <li><a data-categories="">Coming Soon</a></li>
          </ul>
          <ul id="flooring" class="adv-option-set5">
            <li><span class="small">ADV</span> Filter: </li>
            <li><a data-categories="">Coming Soon</a></li>
            <li><a data-categories="">Coming Soon</a></li>
          </ul>
          <ul id="toilets" class="adv-option-set6">
            <li><span class="small">ADV</span> Filter: </li>
            <li><a data-categories="">Coming Soon</a></li>
            <li><a data-categories="">Coming Soon</a></li>
          </ul>
          <ul id="accessories" class="adv-option-set7">
            <li><span class="small">ADV</span> Filter: </li>
            <li><a data-categories="">Coming Soon</a></li>
            <li><a data-categories="">Coming Soon</a></li>
          </ul>
        </div>
      </article>

最终编辑:这是我所拥有的JS代码的另一部分,似乎你的答案实际上也将这部分生效:

    $("#advfilter ul").hide();
    $('.option-set a').on('click', function() {
        $("#advfilter ul").hide();
        $("#advfilter").removeClass('hidden');
        $("#" + $(this).attr('data-subid')).show();
        /*location.href='#filter'*/
    });

    $('.option-set a').click(function()
    {
        // if clicked item is selected then deselect it
        if ($(this).hasClass('selected'))
        {
           $('.adv-option-set1 a').removeClass('selected');
           $('.adv-option-set2 a').removeClass('selected');
           $('.adv-option-set3 a').removeClass('selected');
           $('.adv-option-set4 a').removeClass('selected');
           $('.adv-option-set5 a').removeClass('selected');
           $('.adv-option-set6 a').removeClass('selected');
           $('.adv-option-set7 a').removeClass('selected');
        }

        // otherwise deselect all and select just this one
        else
        {
           $('.option-set a').removeClass('selected');
           $(this).addClass('selected');
           $('.adv-option-set1 a').removeClass('selected');
           $('.adv-option-set2 a').removeClass('selected');
           $('.adv-option-set3 a').removeClass('selected');
           $('.adv-option-set4 a').removeClass('selected');
           $('.adv-option-set5 a').removeClass('selected');
           $('.adv-option-set6 a').removeClass('selected');
           $('.adv-option-set7 a').removeClass('selected');
        }
    });

4 个答案:

答案 0 :(得分:3)

选项#1将是一个简单的循环:

for (var i=1; i<=7; i++) (function(){
    var links = $('.adv-option-set'+i+' a');
    links.click(function() {
        var $this = $(this);
        if (!$this.hasClass('selected')) { // could be left out
            links.removeClass('selected');
            $this.addClass('selected');
        }
    });
})();

请注意,此代码不会删除任何类,因为您对.adv-option-set3的注释(而非代码)(“ ...然后取消选择”)暗示,它“ do当项目已被选中时,[es] nothing “。如果要启用删除类,可能需要在处理程序中使用此代码段:

if ($(this).toggleClass('selected').hasClass('selected'))
    links.not(this).removeClass('selected');

选项#2将为所有链接设置相同的事件处理程序(更好:使用委托事件)并获取应该动态删除类的兄弟链接。此代码取决于您的DOM设置。


好的,现在我看到你的dom我有一些额外的分数。

  • 这些课真的没用。您似乎使用它来标识一个元素 - 该元素已由其id标识。在所有这些文件上使用(相同)class="adv-option-set" 对其进行分类

    选项#2的代码 - 既优雅又高效 - 将如下所示:

$("#advfilter").on("click", "a", function(e) {
    $(this).addClass('selected')
      .closest(".adv-option-set").find("a").not(this).removeClass('selected');
});
// or, little better but tightier bound to the DOM:
$("#advfilter").on("click", "a", function(e) {
    $(this).addClass('selected')
      .parent().siblings().find("a").removeClass('selected');
});
  • 我不确定,但你应该真正看看传统的单选按钮来构建你的表单。完成后,您可以使用一些JavaScript来增强它。

答案 1 :(得分:3)

$('[class^=adv-option-set] a').click(
    function()
    {
       $(this).addClass('selected');
       $('[class^=adv-option-set] a').not(this).removeClass('selected');
    }
);

答案 2 :(得分:1)

呀。但首先,代码没有意义。你说“否则取消选择所有并选择这一个”,但实际上你取消选择这一个然后重新选择它。首先,为所有人提供一个共同的类名。然后,使用jQuery,您可以:

$(".commonClassName").each(function(index, item){
    item.click(function(){
        $(".commonClassName").removeClass('selected');  //no matter what, deselect all of them
        if(!item.hasClass('selected'))
        {
            item.addClass('selected');  //then select this one if it isn't already
        }
    }
});

答案 3 :(得分:0)

你可以在jQuery中使用starts,如下所示:

$('div[class^="adv-option-set"] a').click(function()
{

   // if clicked item is selected then do nothing
   if ($(this).hasClass('selected'))
   {
   }else
   {
     $('div[class^="adv-option-set"] a').removeClass('selected');
     $(this).addClass('selected');
   }

}

我希望这会有所帮助,这个被称为属性的开始,下面的选择器是参考链接供你查看: http://api.jquery.com/attribute-starts-with-selector/

这是我认为最短的代码,我正在跳跃

谢谢Ankur