2014-01-16 21 views
0

我有下面的XML:用document.write()的改變整數值

<beanRepresentation> 
    <beanRepId>222</beanRepId> 
    <beanRepName>Bean 1</beanRepName> 
    <topY>10</topY> 
    <leftX>10</leftX> 
    <height>10</height> 
    <width>10</width> 
</beanRepresentation> 

此行得到TOPY的價值:

document.write(x[i].getElementsByTagName("topY")[0].childNodes[0].nodeValue); 

這會給我10,但我想要一個20,我試圖

document.write(x[i].getElementsByTagName("topY")[0].childNodes[0].nodeValue +10); 

但它沒有工作,它給了我1010而不是。我能做些什麼操作數字?

+1

你是什麼意思它究竟做了什麼?因此,我懷疑你有'1010'這樣的東西,因爲nodeValue是一個字符串,而不是一個數字。 –

+0

是的,它給了我1010 – PhoonOne

+0

那麼,你去。 Javascript看到'nodeValue'是一個字符串,所以它將你的號碼轉換爲一個字符串,並將它們混合在一起。爲了得到真正的數學,你必須將'nodeValue'轉換爲數字。 –

回答

1

nodeValue返回的值是一個字符串(例如,請參閱MDN on this),因此您正在執行字符串連接而不是加法。你應該將結果轉換爲一個數字之前:

document.write(parseInt(x[i].getElementsByTagName("topY")[0].childNodes[0].nodeValue, 10) + 10); 

無論如何,我建議你閱讀關於這個問題的答案:「它不工作」 Why is document.write considered a "bad practice"?

+0

謝謝你的解決方案! – PhoonOne