2012-11-14 70 views
1

我有以下HTML:的jQuery 1.4.2,獲取並替換文本的第一個字符

<span class="drop_cap">3 <span>Dinners</span></span> 

我希望替換第一個字符。該數量將根據用戶的交互變化,所以我不能只抓 「3」

我已經試過:

$("drop_cap").text().substr(0,1).replace(var); 

$("drop_cap").html().substr(0,1).replace(var); 

和類似的事情。

TIA

+0

首先閱讀JS docs for'replace' – Madbreaks

+1

並瞭解'replace'不會改變一個字符串的位置,你必須指定'replace'的結果返回 –

回答

2

jQuery是不是在處理文本節點非常好。既然您知道要編輯跨度內的第一個節點(文本節點),您可以執行以下操作。

// This inserts 100 in front of that text node inside drop_cap 
$("span.drop_cap").each(function(){ 
    this.firstChild.nodeValue = "100" + this.firstChild.nodeValue; 
}); 

下面是一個使用String.replace

$("span.drop_cap").each(function(i){ 
    this.firstChild.nodeValue = this.firstChild.nodeValue.replace(/\d/, i); 
}); 

例爲例:http://jsfiddle.net/rLGPW/2/http://jsfiddle.net/rLGPW/3/

+0

字符串replace正是我所需要的。 –

0

變通,這很容易,特別是如果你只是使用的數字:

<input id='number' type='text' readonly='readonly' value='3'> 

現在你可以使用J-查詢,更改輸入的值,這是一噸比嘗試更改html更少的bug。

$("#number").val(var); 

,並確保你因爲默認情況下CSS輸入框有時髦的輸入框樣式

0

如果你知道總有一個數字,那麼只有一些文字,我想你可以使用一個簡單的正則表達式提取數字:

var num = $('span.drop_cap').text().match(/\d+/)[0] 
+1

OP不想提取數字,他們正在尋找取代它 –

相關問題