DRY programming with jquery

Posting as a jquery newbie . I am sure there should be a way to condense the code below in a dry way. Essentially, it's just show / hide, which applies to multiple elements on a page, using all the same templates and naming conventions:

$("#homelink1").hover(
    function() { $("#poptext1").show(); },
    function() { $("#poptext1").hide(); }
);

$("#homelink2").hover(
    function() { $("#poptext2").show(); },
    function() { $("#poptext2").hide(); }
);
...

I focused on how to convert this to a function with the parameters passed, so that I could just pass an integer (1 or 2) and evaluate the function of the others, for example.

$("#homelink" + param).hover

+3
source share
5 answers

How about this:

function setHover( param ){
   $("#homelink" + param).hover(
    function() { $("#poptext" + param).show(); },
    function() { $("#poptext" + param).hide(); }
  );
}
+5
source

#poptext #homelink? , "homelink" "poptext", - :

$(".homelink .poptext").hover(
    function() { $(this).show(); },
    function() { $(this).hide(); }
});

jQuery , . , $( ". Homelink.poptext" ) , mouseover mouseout hover().

+2

- :

$('.homelink').bind('hover', function(){
    $('.poptext', this).toggleClass('hide');
});

# and some CSS

.hide {
    display: none
}

, , , #homelink {somenumber} #poptext {somenumber}. , (, ), .

+2

, homelink, , poptext.

: http://jsfiddle.net/xFR3s/

$("#homelink1,#homelink2").hover( function() { 
    $("#poptext" + this.id.match(/\d+$/)[0]).toggle(); 
});​

" " homelink. , DOM, , , .

: http://jsfiddle.net/xFR3s/1/

$("[id^=homelink]").hover( function() { 
    $("#poptext" + this.id.match(/\d+$/)[0]).toggle(); 
});​

: , " ", , - :

: http://jsfiddle.net/xFR3s/2/

$("[id^=homelink]").each(function() {
    var num = this.id.match(/\d+$/)[0];
    $(this).hover( function() { 
        $("#poptext" + num).toggle(); 
    });​
});

:

: http://jsfiddle.net/xFR3s/3/

$("[id^=homelink]").each( function() {
    $(this).hover( setUpHover(this.id.match(/\d+$/)[0]) );
});

function setUpHover(num) {
    return function() {
        $("#poptext" + num).toggle(); 
    };
}​
+2

:

jQuery('.homelink').each(function() {
    var me = jQuery(this);
    var target = me.find('.poptext'); //if the target is 'poptext' class
    me.hover(
        function() {
           target.show();
        },
        function() {
            target.hide();
        }
    );
});
0

Source: https://habr.com/ru/post/1753595/


All Articles