简体   繁体   中英

How to change id name with a jQuery function?

Here's the code in question:

function incepeSlider(){
numaratoare = $('.sectiune_chic').size();
loop = setInterval (function(){
        if(slideSecund > numaratoare){
            slideSecund = 1;
            slidePrim = 1;
            }
        $('.sectiune_chic').fadeOut(1000);
        $('#chic' + slideSecund).fadeIn(1000);
        slidePrim = slideSecund
        slideSecund = slideSecund + 1;
    },6000)}

The goal is to create a function that replaces the word chic with funky in the entire script so that the script runs but on other ids. I want to create buttons that when clicked would replace the script above with:

function incepeSlider(){
numaratoare = $('.sectiune_funky').size();
loop = setInterval (function(){
        if(slideSecund > numaratoare){
            slideSecund = 1;
            slidePrim = 1;
            }
        $('.sectiune_funky').fadeOut(1000);
        $('#funky' + slideSecund).fadeIn(1000);
        slidePrim = slideSecund
        slideSecund = slideSecund + 1;
    },6000)

}

these are some examples of what I tried:

function activeazaFunky(){
$('chic').replaceWith('funky');}

,

function activeazaFunky(){
chic = funky;}

Since you already have a function, why not make the part that is variable, the ID, a parameter of the function?

function incepeSlider(id){
    numaratoare = $('.sectiune_' + id).size();
    loop = setInterval (function(){
        if(slideSecund > numaratoare){
            slideSecund = 1;
            slidePrim = 1;
        }
        $('.sectiune_' + id).fadeOut(1000);
        $('#' + id + slideSecund).fadeIn(1000);
        slidePrim = slideSecund
        slideSecund = slideSecund + 1;
    },6000)
}

to be called as

incepeSlider('chic');
// or
incepeSlider('funky');

You should probably also make those variables inside the function local (use the var keyword).

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