Multiple instances of the same jquery script

if I have a script, but it should be run several times on the page, for example, in cms, for example, how do you approach this? in one experiment, I executed the code several times, but I put the article identifier at the end of the selectors that could have knocked down the commands and what needed to be manipulated. this is not a good workaround, although it causes too much code duplication (although it works).

here is an example with which I got help in a recent discussion (with the addition of an article id (textpattern)):

<script type="text/javascript">
    $(document).ready(function() {
        $('.fullTracksInner<txp:article_id />').hide();
        $('.tracklist<txp:article_id />').click(function() {
            $('.fullTracksInner<txp:article_id />').slideToggle('medium');
            if ($('.fullTracksInner<txp:article_id />').is(':hidden')) {
                $(this).text('Show Tracklist');
            } else {
                $(this).text('Hide Tracklist');
            }
        });
    });
</script>

just imagine, for example, three slide shows on a page using the same slide show script.

+3
source share
2 answers

jQuery. , , $(this), , . , , , , - :

$(document).ready(function() {
 $('.fullTracksInner<txp:article_id />').hide();

    $('.tracklist<txp:article_id />').click(function() {
     $(this).children('.fullTracksInner<txp:article_id />').slideToggle('medium');
        if ( $(this).children('.fullTracksInner<txp:article_id />').is(':hidden') ) {
            $(this).text('Show Tracklist');
        } else {
            $(this).text('Hide Tracklist');
        }
    });
});

, , , , , $('.tracklist<txp:article_id />') .

+2

JavaScript, , .

<script type="text/javascript">
function performSlide(tracklist) {
    var fulltracks = $('.fullTracksInner<txp:article_id />');

    $(fulltracks).slideToggle('medium');
    if (fulltracks).is(':hidden')) {
        changeText(tracklist, 'Show Tracklist');
    } else {
        changeText(tracklist, 'Hide Tracklist');
    } 
}

function changeText(textbox, text) {
    textbox.text(text);
}

$(document).ready(function() {
    var tracklist = $('.tracklist<txp:article_id />');

    tracklist.click(function() {
        performSlide(tracklist);
    });

    $('.someRadioButton').change(function() {
        performSlide(tracklist); 
    });
});
</script>
0

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


All Articles