0

I have many jquery click function, they are very similar, how to combine them for shorter code. (use regex or use array foreach?)

$(".menu").live('click', function() {
    var value = $(this).html();
    $('#menu').html(value);
});

$(".nav").live('click', function() {
    var value = $(this).html();
    $('#nav').html(value);
});

$(".list").live('click', function() {
    var value = $(this).html();
    $('#list').html(value);
});
2
  • Question! Are .menu, .nav, and .list all children of some node in your tree besides document? Commented Oct 10, 2011 at 20:44
  • all in first child nod of <body> Commented Oct 10, 2011 at 20:46

2 Answers 2

2

This should do:

var elems = ["menu", "nav", "list"];
$.each(elems, function(i, elem){
    $("."+elem).live('click',function(){
        var value = $(this).html();
        $('#'+elem).html(value);
    });
});
  1. Create a list of elements.
  2. Loop through it using $.each
  3. The second argument of the function equals the element in the list (menu, nav, ..)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that is easier than I image.
2

Rob's answer is definitely vote-up-worthy, but I just wanted to say that sometimes you want to limit the arbitrary connections between two elements. Why should element X have a class that MUST be the same name as element Y's ID? It's pretty arbitrary and can be a hassle for people to later figure out.

You can instead approach it like this to make it more robust:

<a href="#" class="foo" data-your-data-attr="alice">alice</a>
<a href="#" class="foo" data-your-data-attr="bob">bob</a>
<a href="#" class="foo" data-your-data-attr="sue">sue</a>

Now your JS becomes super straight-forward and easy:

$(".foo").live('click',function(){
    var value = $(this).html();
    var yourDataAttr= $(this).data('yourDataAttr');
    $('#' + yourDataAttr).html(value);
});

2 Comments

Note that data attributes should be hyphen-separated, not camelCase. jQuery handles the transition for you - .data('yourDataAttr') will refer to data-your-data-attr.
@Eric Most accurate, my mistake on that one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.