簡體   English   中英

javascript從<a href>鏈接</a>解析文本

[英]javascript parse text from <a href> links

可以說我有

<a href="/example1">ThisTextChanges</a>
<a href="/example2">ThisTextChanges</a>
<a href="/example3">ThisTextChanges</a>
<a href="/example4">ThisTextChanges</a>

我想遍歷這些並獲得“ ThisTextChanges”,這是一些會更改的數字,最准確地說是計時器。

我該如何實現? jQuery很好。 它們位於id為“ main_container”的div中。 我需要將文本放在一個變量中,因此href很重要,以便知道我為每個變量使用哪個變量。

讓我們將任務分為幾個步驟:

  • 獲取所有鏈接的句柄( document.querySelectorAll
  • 學習如何得到目前的案文a標簽( childNode[0].nodeValue

  • 全部放在一起( Array.fromArray.map

獲取我們所有鏈接的句柄:

我們將使用document.querySelectorAll獲取與選擇器匹配的所有節點的列表。 在這里,我將使用選擇器a ,但是您可能有一個類,用於指定這些鏈接與頁面上的其他鏈接:

var links = document.querySelectorAll('a');

獲取鏈接文本

這個有點復雜。 有幾種方法可以做到這一點,但是一種更有效的方法是遍歷子節點(主要是文本節點),並為每個子節點附加node.nodeValue 我們可能只使用第一個孩子的nodeValue就可以逃脫,但是我們將構建一個循環遍歷並追加每個孩子的函數。

function getText(link){
    var text = "";
    for (var i = 0; i < link.childNodes.length; i++){
        var n = link.childNodes[i];
        if (n && n.nodeValue){
            text += n.nodeValue;
        }
    }
    return text;   
} 

放在一起

綜上所述,我們將使用Array.map將列表中的每個鏈接轉換為其中的文本。 這將給我們留下一堆字符串。 但是,為了能夠將其傳遞給Array.map我們將必須具有一個數組,而document.querySelectorAll返回一個NodeList 因此,要對其進行轉換,我們將使用Array.fromNodeList轉換為數組。

 function getText(link){ var text = ""; for (var i = 0; i < link.childNodes.length; i++){ var n = link.childNodes[i]; if (n && n.nodeValue){ text += n.nodeValue; } } return text; } var linkTexts = Array.from(document.querySelectorAll('a')) .map(getText); console.log(linkTexts); 
 <a href="1">this is text</a> <a href="2">this is some more text</a> 

您可以迭代並將它們存儲在數組中

var arr = [];   

$("a").each(function(){

  arr.push($(this).text());
  console.log( arr );

});

您可以通過多種方式實現這一目標。 此示例使用for loop

var main_container = document.getElementById("main_container");
var items = main_container.getElementsByTagName("a");
for (var i = 0; i < items.length; ++i) {
      // do something.....
}

 var array = []; $('#main_container a').each(function(){ array.push($(this).html()); }); console.log(array); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="main_container"> <a href="/example1">ThisTextChanges 1</a> <a href="/example2">ThisTextChanges 2</a> <a href="/example3">ThisTextChanges 3</a> <a href="/example4">ThisTextChanges 4</a> </div> 

請試試:

$('#main_container > a[href]').each(function() {
    var tes = $(this).attr('href').substring(1);
    window[tes] = $(this).text();
});

<a href="/example1">123</a>將產生名為example1 var值123 ,依此類推。

您可以僅在a選擇器中添加條件,如下所示:

var array = [];
$('#main_container a[href="/example2"]').each(function(){
   array.push($(this).html());
});
console.log(array);

暫無
暫無

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

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