Use an inner.HTML mathematically?

被刻印的时光 ゝ 提交于 2019-12-11 19:18:28

问题


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:


  1. You have to actually get the innerHTML (you are currently looking at the HTML element node)
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!