javascript replace text in span
I was looking around and found this code and tried to get it working but no luck. Basically if you click the button it is suppose to replace the text in the span with Hello world.
<script type="text/javascript">
$(function(){
$("#change").click(function(){
var onlineSpan = $("#people").text().replace("Hello World");
$("#people").text(onlineSpan);
});
$("#refresh").click(function(){
location.reload();
});
});
</script>
<span id="people">content to replace</span>
<button id="change"> Change </button>
What I would like to do is replace the text in the span but use an array to update the span every 60 seconds with a random entry from the array instead of using a button. Also the span is located inside an iframe and this iframe is on the same domain.
iframe 1
var myCars = new Array();
myCars[0] = "Saab";
myCars[1] = "Volvo";
myCars[2] = "BMW";
$(function(){
$("#change").click(function(){
var carSpan = $("#cars").text().replace(myCars);
$("#cars").text(carSpan);
});
});
iframe 2
<开发者_StackOverflow中文版span id="cars">content to replace</span>
For executing Javascript at an interval (every 60 seconds), use setInterval. To get a random number, use Math.random() as described here.
var myCars = new Array();
myCars[0] = "Saab";
myCars[1] = "Volvo";
myCars[2] = "BMW";
function changeCars() {
var randomI = Math.floor(Math.random()*myCars.length);
var carSpan = $("#cars").html(myCars[randomI]);
}
$(document).ready(function(){
setInterval(changeCars, 60000);
});
You can see this in action.
well, in case you want to append new value to the span:
var carSpanText = $('#cars').text(),
randomnum = Math.floor(Math.random() * myCars.length);
$('#cars').text( carSpanText + myCars[randomnum] );
if you need to just replace the text then:
var randomnum = Math.floor(Math.random() * myCars.length);
$('#cars').text( myCars[randomnum] );
精彩评论