繁体   English   中英

之后如何获取文字 <br> 标签

[英]how to get the text after <br> tag

如何获取<br/> tag后的所有text

我的HTML是这样的

<i class="loc">cherry<br>From Shimla</i>
<i class="loc">Apple<br>from kashmir</i>
<i class="loc">banana<br>From bihar</i>

预期的输出: ["From Shimla","from kashmir","From bihar"];

我正在尝试这样的事情

 var arr = []; $('.loc').each(function(){ arr.push($(this).text()); }); console.log(arr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <i class="loc">cherry<br>From Shimla</i> <i class="loc">Apple<br>from kashmir</i> <i class="loc">banana<br>From bihar</i> 

您可以定位br元素,并使用.get(index)来获取底层的DOM元素,使用nextSibling来定位文本节点。 然后,可以使用nodeValue属性获取文本。

 var arr = []; $('.loc').each(function() { arr.push($(this).find('br').get(0).nextSibling.nodeValue); }); console.log(arr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <i class="loc">cherry<br>From Shimla</i> <i class="loc">Apple<br>from kashmir</i> <i class="loc">banana<br>From bihar</i> 

您可以进一步改善代码

 var arr = $('.loc').map(function() { return $(this).find('br').get(0).nextSibling.nodeValue; }).get(); console.log(arr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <i class="loc">cherry<br>From Shimla</i> <i class="loc">Apple<br>from kashmir</i> <i class="loc">banana<br>From bihar</i> 

var arr = [];

$('.loc').each(function(){
   arr.push($(this).html().split('<br>')[1]);
});
console.log(arr);

您可以使用html()对其进行拆分,并使用数组中的第二个值。

 var arr = []; $('.loc').each(function(){ arr.push($(this).html().split('<br>')[1]); }); console.log(arr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <i class="loc">cherry<br>From Shimla</i> <i class="loc">Apple<br>from kashmir</i> <i class="loc">banana<br>From bihar</i> 

var arr = [];

    $('.loc').each(function(){
        arr.push($(this).children('br').get(0).nextSibling);
    });
console.log(arr);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM