简体   繁体   中英

jquery combine similar code

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);
});

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 , ..)

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM