簡體   English   中英

在javascript參數中將字符串轉換為Integer

[英]convert string to Integer in a javascript parameter

我有一個javascript函數,它帶有兩個參數:第一個參數是給定html分區的ID,第二個參數是resultSet行的內容(從數據庫返回)。

    function displayItem(item_ID, content)
    {  
        alert(typeof(item_ID)); // this one returns a String
        el = document.getElementById(item_ID);
        alert(el);

      dispArea=document.getElementById("individual");
      dispArea.innerHTML=content; 

  }

當我嘗試在我的鏈接之一中調用函數時,就會出現問題:

     <ul id="principle_items">
                             <!--  <%int x=0; %> !-->
                             <c:set value ="0" var="x" />
                             <c:forEach var="row" items="${result.rows}">
                             <c:set value ="${x+1}" var="x" />
                            <!--  <% out.println("the value of X is " + x +"\n");%>  !-->

                             <li><a id="${x}" href="#" onclick="displayItem(this.id,'${result.rows[8].PRNCPL_NAME}');"><c:out value="${row.PRNCPL_NAME}"/></a></li>
                            </c:forEach>
         </ul>

而不是選擇reslut.rows [8],我希望索引是this.id的整數值(我所有的ID均為“ 1”,“ 2”,“ 3” ...)
onclick =“ displayItem(this.id,'$ {result.rows [8] .PRNCPL_NAME}');”

當我嘗試onclick =“ displayItem(this.id,'$ {result.rows [this.id] .PRNCPL_NAME}');”時;“ 它顯然不起作用,因為this.id是一個字符串。 我知道我可以在Java中使用parseInt,但是如果在同一條語句中,我不確定該怎么辦。

使用parseInt函數

alert(typeof(parseInt(item_ID)));
//should be "number"

演示

 var item_ID = "7"; alert(typeof(parseInt(item_ID))); 

認為問題在於JSP和JavaScript的解析。 它們在不同的時間完成。 因此,您無法在JSP解析時運行JavaScript。

所以您的ID只是$ {x} ,您不能只將x像這樣放入代碼中嗎?

onclick="displayItem(this.id,'${result.rows[x].PRNCPL_NAME}');"

還是類似的東西?

你會想使用parseInt中描述塔里克·馬哈茂德的答案 ,但parseInt功能也接受這會導致始終使用該閱讀基地某些數字就像當防止潛在的錯誤計算值的基數 08的實例。

從MDN:

基數

2到36之間的整數,表示上述字符串的基數(數學數字系統中的基數)。 為人類常用的十進制系統指定10。 始終指定此參數,以消除讀者的困惑並保證可預測的行為。 當未指定基數時,不同的實現產生不同的結果,通常將值默認為10。

您的功能變為:

function displayItem(item_ID, content) {
    var item_ID = parseInt(item_ID, 10);  
    alert(typeof(item_ID)); // this one returns a String
    el = document.getElementById(item_ID);
    alert(el);

    dispArea = document.getElementById("individual");
    dispArea.innerHTML=content; 

}

如果您必須使用十進制數字,那么可能是兄弟parseFloat可以為您提供幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM