簡體   English   中英

使用javascript獲取標簽之間的文本

[英]Get text between tags using javascript

我試圖從跨度標簽之間獲取價格。 我想將所有價格都放在一個數組中。 我似乎無法讓它工作,我猜我的正則表達式不正確。

我正在尋找具有“數量”類的任何跨度標簽,該標簽沒有設置其他屬性並且只有一個類。 例如<span class="amount">&pound;9.99</span>

var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
    .map(function(val){
      return val;
});

輸出

[ '&pound;9.99', '&pound;100.00' ]

我試圖從跨度標簽之間獲取價格。 我想將所有價格都放在一個數組中。 我似乎無法讓它工作,我猜我的正則表達式不正確。

我正在尋找具有“數量”類的任何跨度標簽,該標簽沒有設置其他屬性並且只有一個類。 例如<span class="amount">&pound;9.99</span>

var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
    .map(function(val){
      return val;
});

輸出

[ '&pound;9.99', '&pound;100.00' ]

* 更新 *

原來這是一個帶有 ajax 響應resp.fragments['data']的編碼。

我正在使用正則表達式,因為它是我之前在 JS 中沒有真正使用過的東西,我想我會玩。 我確實看過很多例子,在大約 45 分鍾沒有成功之后,我認為一組新的眼睛會修復它。

@spaceman 感謝您的有用評論。 如果有人問“房子里有醫生嗎?”,你就是其中的一個,你會站起來說“甜蜜的負擔,外面有很多醫生”。

雖然正則表達式可以解決這個問題,但簡單地選擇<span class='amount'>元素並通過map()函數將它們的innerHTML內容映射到數組可能更容易:

// This would yield an array containing your values
var amounts = Array.prototype.slice
                             .call(document.querySelectorAll('span.amount'))
                             .map(function(a){ return a.innerHTML; });

您可以在此處查看演示的工作示例

您可以改用它。

 var prices = document.getElementsByClassName('amount'); var price_array = []; for (i= 0; i < prices.length; ++i) { price_array.push(prices[i].innerHTML); } document.write(" | " + price_array);
 <span class='amount'>&pound;123</span> <span class='amount'>&pound;3</span> <span class='amount'>&pound;5</span> <span class='amount'>&pound;64</span>

您不需要為此使用正則表達式或 jQuery。

最簡單的方法是將它添加到一個不可見的 DOM 對象,然后通過 DOM API 遍歷它

var text  = '<span class="amount">&pound;9.99</span><span class="amount">&pound;9.99</span>'

//現在將它附加到一個DOM對象

var wrapperDiv = "<div style='display:none' id='tmpDiv'>" + text + "</div>";
document.body.innerHTML += wrapperDiv;

var elements = document.querySelectorAll( "#tmpDiv amount" );
var output = Array.prototype.slice.call( elements ).map( function(val){
  return val.innerText;
})

另一種方法可以通過<span class="amount"> split文本並在第一個索引后獲取值

演示

 var text = '<span class="amount">&pound;9.99</span><span class="amount">&pound;9.99</span>' var output = []; text.split('<span class="amount">').forEach( function(val, index) { if (index > 0 ) { output.push( val.replace( "</span>", "" ) ); } }); document.body.innerHTML += JSON.stringify( output, 0, 4 );

暫無
暫無

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

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