我正在尋找通過整個網站尋找英制單位(例如磅,英尺和英寸)並將它們轉換爲度量值,公制,米,釐米的方法。查找所有英制單位,並用其公制單位替換
例子:
<main>
<h1>Top speed of new car is 300mph/h</h1>
<p>
Such a fast car, previously going only 250 mph, now topping speeds up to 300mph.
And it only weighs 300lbs, 20 pounds less than before!
</p>
</main>
變爲:
<main>
<h1>Top speed of new car is 482.8km/h</h1>
<p>
Such a fast car, previously going only 402km/h, now topping speeds up to 482.8km/h.
And it only weighs 136kg, 9kg less than before!
</p>
</main>
的問題不是如何從英里/磅轉換成公里每小時/公斤,但如何查找和存儲值例如「10mph」,「10mph」,「200lbs」,「200lbs」,「200磅」,並將其轉換並最終替換它們。
任何指針都會非常有幫助!
編輯什麼,我想實現一個簡單的例子:
<p>This is 10 lbs</p>
<p>This is 20lbs</p>
<script>
$('p').each(function(){
var text = $(this).text().toLowerCase();
if(text.indexOf('lbs') >= 0) {
// Store "XX lbs" in a variable
// Wrap the above created variable in a <span>
// Convert the variable to kg
// Replace the text in <span> with the value in kilogram
// Output: <p>This is <span>4.5kg</span></p>
}
});
</script>
我想我們可能會讓你開始,但你的一些代碼可能會很好。所以假設所有的文本都是XXXlbs XXXpounds XXX,你可以用類似於variablename = $('div')。html()的方式閱讀文本,然後用js搜索單位,向後搜索前一個空格,抓取數字,做轉換,並替換文字。不是一個小小的追求。 – TimSPQR
這個問題如何與Javascript/jQuery相關? – hindmost
這實際上不可能通過掃描自然文本來完成。首先,考慮用'm'測量的單位。這可能是米,英里或其他幾個。不知道文本的上下文,就會產生無法解決的歧義。其次,許多單位可以用幾種方式書寫:'kph'和'km/h'是一樣的。最後,「帝國」單位的定義不明確:英國英里與美國英里不同。還有其他版本的「里程」也存在。這同樣適用於大多數其他英制單位。再次,在開始之前,您必須確定文本的上下文。 – Spudley