Doing a find and replace of a span in jquery
Ok i have the following code in jquery. I want to do a find and replace in jquery, I want to find the first span and replace it with a variable. So my question is how would i go about finding the first span, and then find the second?
<html>
<head>
<title>JQuery Problem 2</title>
<script type="text/javascript" src="jquery-1.4.min.js"></script>
<script type="text/javascript" src="problem2.js"></script>
</head>
<body>
<div id="game">
<form onsubmit="return false">
<p>
Guess:
<input type="text"/>
<input type="submit" value="Go"/>
</p>
<p>
<strong>Number of guesses:</strong>
<span>0</span>
</p>
<p>
<strong>Last guess:</strong>
<span>None</span>
</p>
<table border="1" cellpadding="4" cellspacing="1" style="width: 400px">
<tr>
<th>Guess</th>
<th>Result</th>
</tr>
</table>
</form>
</div>
</body>
</html>
Here is my jquery
$(document).ready(function()
{
var randomNum = Math.floor(Math.random()*101)
var $guess
var $count = $("#game span")
var guessCount = 0;
开发者_如何学Python var lastGuess;
$(":text").change(function()
{
$guess = $(this).val()
guessCount++;
if (isNaN( parseInt($guess) ))
{
//alert("not a number")
alert($count.html())
}
else if( $guess != randomNum )
{
//alert(randomNum)
}
else
{
//alert("You Win")
}
});
});
Here's one way to do it (I'm assuming here that you are wanting to show the number of guesses and the value they entered as the guess):
$('#game span:eq(0)').text(guessCount);
$('#game span:eq(1)').text($guess);
But personally, I would just put an id on the two spans and use that, unless there's a good reason not to. Wouldn't be as fragile in case you end up sticking another span tag in there above those two at some point.
try find http://api.jquery.com/find/
$('body').find('span') should give all span in your html body.
loop through using .each and replace the text node.
If it's a more complicated page, consider
$('#game form p span')[0]
which can locate the element accurately.
精彩评论