簡體   English   中英

如何使用javascript獲取跨度內的內部文本?

[英]How to get the inner Text inside span using javascript?

鏈接在這里; http://heart.bmj.com/content/early/2016/08/10/heartjnl-2016-310003.long

我有;

<span class="cit-title">
    <span class="cit-series-title">Original article
        <span class="cit-sep cit-sep-after-article-series-title">:</span>
    </span>Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease 
</span>

到目前為止,我做了什么?

我選擇了span.cit-title但它是innerText

給我;

"Original article: Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease"

我只想得到

"Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease"` 

部分。

如何使用類cit-series-title排除span並獲取原始文本?

您想要的文本是.cit-series-title下一個兄弟。 您可以選擇該元素,然后使用javascript Node.nextSibling獲取該元素的下一個同級文本。

 var text = $(".cit-title > .cit-series-title")[0].nextSibling.textContent; console.log(text); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="cit-title"> <span class="cit-series-title">Original article <span class="cit-sep cit-sep-after-article-series-title">:</span> </span>Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease </span> 

您可以首先獲取整個cit-title元素的內容...

var wholeElementText = $('.cit-title').text();

...然后只獲得標題文字...

var titleText = $('.cit-title .cit-series-title').text();

... 然后從整個wholeElementText刪除titleText

var justThePartYouWant = wholeElementText.replace(titleText, '');

span.cit-title選擇數據並將其存儲到變量A ,然后從span.cit-series-title選擇數據並將其存儲到變量B

然后像A.replace(B, ''); 它會工作

 alert($(".cit-title").clone() .children() .remove() .end() .text()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="cit-title"> <span class="cit-series-title">Original article <span class="cit-sep cit-sep-after-article-series-title">:</span> </span>Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease </span> 

我會將div存儲在一個臨時變量中,以刪除不需要的元素並獲取文本。

var div = $(".cit-title").clone();
div.find("span").first().remove();
div.text();

我認為更好的解決方案是將其他文本包裝在另一個跨度中,如下所示:

 <span class="cit-title"> <span class="cit-series-title">Original article<span class="cit-sep cit-sep-after-article-series-title">:</span> </span><span class="cit-series-description">Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease</span> </span> 

然后從.cit-series-description獲取內部文本,而不是從容器中獲取。

干杯

暫無
暫無

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

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