[英]Use an inner.HTML mathematically?
I'm making a script, in which i have to use an inner.HTML which is a number, and work with it mathematically.我正在制作一个脚本,在其中我必须使用一个数字的inner.HTML,并以数学方式使用它。 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:如您所见,inner.HTML 是一个数字,我想制作一个脚本,如:
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.当然,这是不可能的,因为脚本没有将inner.HTML 视为可以在数学上使用的数字。
So, is there a way to convert the inner.HTML into a number I can do math with?那么,有没有办法将 inner.HTML 转换为我可以用它进行数学运算的数字?
Thanks for helping!感谢您的帮助!
You can use unary operator +
for convert string to number something like您可以使用一元运算符
+
将字符串转换为数字,例如
var results = +(document.getElementById("searchResults").innerHTML);
//------------^
Also you forgot to use .innerHTML
你也忘了使用
.innerHTML
You probably need .innerHTML
, as without .innerHTML
your results
will contain HTMLspanobject
you have to do innerHTML
您可能需要
.innerHTML
,因为没有.innerHTML
您的results
将包含HTMLspanobject
您必须执行innerHTML
var results = document.getElementById("searchResults").innerHTML;
alert(parseInt(results));
if (parseInt(results,10) > 3000)
{
alert("te");
// location.reload(true);
}
parseInt
, parseFloat
or the Unary +
Operator (but you probably don't need to since >
is quite smart when the LHS is a number).parseInt
、 parseFloat
或一元+
运算符(但您可能不需要,因为当 LHS 是数字时>
非常聪明)。 Such:这样的:
var results = document.getElementById("searchResults");
var results_num = parseInt( results.innerHTML, 10 );
var results = document.getElementById("searchResults").innerHTML;
if (parseInt(results) > 3000)
{
location.reload(true);
}
InnerHtml returns string content. InnerHtml 返回字符串内容。 You need to convert it to a number/integer.
您需要将其转换为数字/整数。
var results = document.getElementById("searchResults");
if (results != null && parseInt(results.innerHTML) > 3000)
{
location.reload(true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.