繁体   English   中英

随机旋转范围的内容

[英]Randomly rotate content of a span

我正在尝试将文本的<span>更改为七个文本块之一。 我找到了可以使用以下Javascript来帮助我完成操作的教程,但是,它依赖于保存在<ul> 我认为我无法做到这一点,因为我需要将更改后的文本显示在预先存在的段落中。

我在想可能有一种方法可以给span提供一个id,然后在Javascript中设置内容的不同选项。

我只希望更改在页面加载或刷新时随机发生,没有让它发生在用户输入或计时器上那样复杂的事情。

以下是我在教程中找到的脚本,也许只是一个简单修改的​​情况。 不过,我真是个新手,除非明确说明,否则我真的不知道从哪里开始。

<script type="text/javascript">

this.randomtip = function(){
    var length = $("#tips li").length;
    var ran = Math.floor(Math.random()*length) + 1;
    $("#tips li:nth-child(" + ran + ")").show();
};

$(document).ready(function(){   
    randomtip();
});

</script>

像这样的作品:

Java脚本

<script type="text/javascript">
    $(document).ready( function() {

        // hide all of the tips
        $('#tips').children('.tip').hide();

        // randomly select one tip to show
        var length = $("#tips .tip").length;    
        // **EDIT **
        // This code was buggy!
        //var ran = Math.floor(Math.random()*length) + 1;
        //$("#tips .tip:nth-child(" + ran + ")").show();
        // Use this instead:
        var ran = Math.floor((Math.random()*length));
        $('#tips > .tip:eq('+ran+')').show();
    });
</script>

的HTML

<p id="tips">
    <strong>Random Tip: </strong>
    <span class="tip">This is tip 1.</span>
    <span class="tip">This is tip 2.</span>
    <span class="tip">This is tip 3.</span>
    <span class="tip">This is tip 4.</span>
    <span class="tip">This is tip 5.</span>
    <span class="tip">This is tip 6.</span>
    <span class="tip">This is tip 7.</span>
</p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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