问题
I'm making a script, in which i have to use an inner.HTML which is a number, and work with it mathematically. Here's the example:
<span id="searchResults">2301</span>
As you can see, the inner.HTML is a number, and I'd like to make a script like:
var results = document.getElementById("searchResults");
if (results > 3000)
{
location.reload(true);
}
Of course this isn't possible because the script doesn't see the inner.HTML as a number it can mathematically work with.
So, is there a way to convert the inner.HTML into a number I can do math with?
Thanks for helping!
回答1:
You can use unary operator +
for convert string to number something like
var results = +(document.getElementById("searchResults").innerHTML);
//------------^
Also you forgot to use .innerHTML
回答2:
- You have to actually get the innerHTML (you are currently looking at the HTML element node)
- You can use
parseInt
,parseFloat
or the Unary+
Operator (but you probably don't need to since>
is quite smart when the LHS is a number).
Such:
var results = document.getElementById("searchResults");
var results_num = parseInt( results.innerHTML, 10 );
回答3:
You probably need .innerHTML
, as without .innerHTML
your results
will contain HTMLspanobject
you have to do innerHTML
var results = document.getElementById("searchResults").innerHTML;
alert(parseInt(results));
if (parseInt(results,10) > 3000)
{
alert("te");
// location.reload(true);
}
Demo
回答4:
var results = document.getElementById("searchResults").innerHTML;
if (parseInt(results) > 3000)
{
location.reload(true);
}
InnerHtml returns string content. You need to convert it to a number/integer.
回答5:
var results = document.getElementById("searchResults");
if (results != null && parseInt(results.innerHTML) > 3000)
{
location.reload(true);
}
来源:https://stackoverflow.com/questions/22766201/use-an-inner-html-mathematically