Javascript 使用jquery'在三个标头之间旋转;替换为

Javascript 使用jquery'在三个标头之间旋转;替换为,javascript,jquery,Javascript,Jquery,设计用于在三个不同的h3元件之间旋转。它目前可以工作,但看起来很邋遢。当我最终对一个p和一个img元素进行模拟时,它将比需要的要长得多。我对jQuery还比较陌生,所以我想做一些清理和润色 HTML: 第一副标题 jQuery: setInterval(function() { if($("#subtitle1").length) { $('#subtitle1').replaceWith("<h3 id='subtitle2'>second subtitl

设计用于在三个不同的h3元件之间旋转。它目前可以工作,但看起来很邋遢。当我最终对一个p和一个img元素进行模拟时,它将比需要的要长得多。我对jQuery还比较陌生,所以我想做一些清理和润色

HTML:

第一副标题
jQuery:

setInterval(function() {
    if($("#subtitle1").length) {
        $('#subtitle1').replaceWith("<h3 id='subtitle2'>second subtitle</h3>");
    } else if($("#subtitle2").length) {
        $('#subtitle2').replaceWith("<h3 id='subtitle3'>third subtitle</h3>");
    } else if($("#subtitle3").length) {
        $('#subtitle3').replaceWith("<h3 id='subtitle1'>first subtitle</h3>");
    }
}, 2000);
setInterval(函数(){
如果($(“#子标题1”).长度){
$(“#副标题1”)。替换为(“第二副标题”);
}else if($(“#副标题2”).长度){
$(“#副标题2”)。替换为(“第三副标题”);
}else if($(“#子标题3”).长度){
$(“#副标题3”)。替换为(“第一副标题”);
}
}, 2000);

这只是一个示例-您必须修改它以满足您的确切需要

HTML

<h3 id="header-title">This is some title text</h3>
<p id="header-text">This is some text</p>
<img id="header-image" src="./images/something.jpg" />
它只需循环遍历您在阵列中所做的所有更改
mods
,每20秒进行一次更改。添加/删除属性并更改间隔中的函数以适合您的页面


您还可以随意扩展数组中的元素数量,而不必破坏它。

可能重复到,您说的“sloppy”是什么意思?javascript代码中包含大量html,这是一个坏习惯。我会将所有三个标题都放在html中,并通过给它们一个类“hidden”来隐藏其中两个标题。在jquery中,您可以使用addClass(“隐藏”)和removeClass(“隐藏”),也可以检查“没有问题”-很乐意帮助:)
<h3 id="header-title">This is some title text</h3>
<p id="header-text">This is some text</p>
<img id="header-image" src="./images/something.jpg" />
var mods = [{
        title: "This is header text 1",
        text: "This is paragraph text 1",
        image: "./images/header-image-01.jpg"
    }, {
        title: "This is header text 2",
        text: "This is paragraph text 2",
        image: "./images/header-image-02.jpg"
    }, {
        title: "This is header text 3",
        text: "This is paragraph text 3",
        image: "./images/header-image-03.jpg"
    }];

var counter = 0;

setInterval(function() {
    counter = (counter + 1) % mods.length;

    $("#header-title").text(mods[counter].title);
    $("#header-text").text(mods[counter].text);
    $("#header-image").attr("src", mods[counter].image);

}, 20000);