Randomly rotate content of a span

2019-09-01 17:31发布

问题:

I'm trying to change a <span> of text to one of seven chunks of text. I've found a tutorial that can help me do it using the Javascript below, however, it relies on the selections being kept in a <ul>. I don't think I can do that, because I need the changed text to appear within a pre-existing paragraph.

I'm thinking there might be a way to give the span an id, and then, within the Javascript, set the different options the content could be.

I only want the change to happen randomly as the page loads or is refreshed, nothing complicated like having it happen on a user input or on a timer.

Below is the script I found on the tutorial, maybe it's just a case of a simple amendment. I'm such a newbie, though, I don't really know where to start unless it's spelt out.

<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>

回答1:

Something like this works:

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>