2
\$\begingroup\$

I am using jQuery's collapsible lists grouped and named #List01, #List02, #List03, etc. My code captures clicks on list elements and remembers list items' ID for further processing. Each group has identically looking code so I was wondering how I could encapsulate it in one function.

$(document).on('click', '#List01 li', function ()
{
    var anchor = $(this).find('a');
    sessionStorage.KenID = anchor.attr('id');
    changePage();
});
$(document).on('click', '#List02 li', function ()
{
    var anchor = $(this).find('a');
    sessionStorage.KenID = anchor.attr('id');
    changePage();
});
$(document).on('click', '#List03 li', function ()
{
    var anchor = $(this).find('a');
    sessionStorage.KenID = anchor.attr('id');
    changePage();
});
\$\endgroup\$
  • \$\begingroup\$ why dont just use class as jquery selector since the function have no relation with it? \$\endgroup\$ – Charlie Apr 10 '13 at 5:21
  • \$\begingroup\$ with jquery i don't thinks its anymore posible just find leaks in your code, optimize by hand and make it in one file and exucute part of code only on page, where it needs, for example many site have lots of jquery code running on every page, if page url is xyz then run this code only, and you should try clouse compiler to optimize it and use zepto instead of jquery (if you can afford), \$\endgroup\$ – Meghraj Choudhary Apr 10 '13 at 5:23
1
\$\begingroup\$
$(document).on('click', '#List01 li, #List02 li, #List03 li', function () {
        var anchor = $(this).find('a');
        sessionStorage.KenID = anchor.attr('id');
        changePage();
});

The , should do the trick.

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

One handler will do all this:

$(document).on('click', '[id^=List] li', function ()
    {
        var anchor = $(this).find('a');
        sessionStorage.KenID = anchor.attr('id');
        changePage();
    });

see: http://www.w3.org/TR/css3-selectors/#attribute-substrings

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy