0

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

我在想可能有一种方法可以给跨度一个 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>
4

1 回答 1

0

像这样的工作:

Javascript

<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>
于 2013-08-07T14:57:21.403 回答