在结果字符串中的元素之间插入分隔符

时间:2017-10-26 16:55:33

标签: jquery

我想重复使用breadcrumbs结构来获得友好的SEO类别标题。如何使用LinearRegressor函数在输出中获取分隔符(/)?

提前致谢!



.text()

$(function(){
    var str = $( ".breadcrumb-element").text();
    $( "p.text22" ) .html( str );
}); 




2 个答案:

答案 0 :(得分:1)

嗯,这是CSS的内容 只需定义:在伪元素之后显示分隔符。

示例:

.breadcrumb-element:after {
  content: '/';
  padding: 0 5px;
}

.breadcrumb-element:last-child:after {
  content: '';
}

使用JS对此有点臃肿。但只是我的5美分。



.breadcrumb-element {
  text-decoration: none;
}

.breadcrumb-element:after {
  content: '/';
  padding: 0 5px;
}

.breadcrumb-element:last-child:after {
  content: '';
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div class="breadcrumb">
<a class="breadcrumb-element" href="#" title="Go to Sale">Sale</a>
<a class="breadcrumb-element" href="#" title="Go to Accessories">Accessories</a>
<a class="breadcrumb-element" href="#" title="Go to Scarves">Scarves</a>
</div>


<br><br><br><br>

<p class="text22"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用.text()中的函数来检查元素的索引,如果它不是第1个元素,请在文本前插入/

$( ".breadcrumb-element").text(function(i, t){
str += i == 0 ? t : '/' + t;
});

JSFiddle

&#13;
&#13;
var str = '';
$( ".breadcrumb-element").text(function(i, t){
str += i == 0 ? t : '/' + t;
});
$( "p.text22" ) .html( str );
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="breadcrumb">
<a class="breadcrumb-element" href="#" title="Go to Sale">Sale</a>
<a class="breadcrumb-element" href="#" title="Go to Accessories">Accessories</a>
<a class="breadcrumb-element" href="#" title="Go to Scarves">Scarves</a>
</div>


<br><br><br><br>

<p class="text22"></p>
&#13;
&#13;
&#13;