交换单词跨度

时间:2017-09-04 16:16:53

标签: javascript jquery

我有几个这样的跨度:

<span class="test">word1 word2 @ different content test </span>
<span class="test">word3 word4 @ different content test343wer</span>
<span class="test">example54 example98 @ different content3453</span>
<span class="test">word13 word92 @ different content1111111</span>
<span class="test">word223 word14 @ different content00</span>

我需要这个输出:

<span class="test">word2 word1</span>
<span class="test">word4 word3</span>
<span class="test">example98 example54</span>
<span class="test">word92 word13</span>
<span class="test">word14 word223</span>

请注意,前两个单词已交换位置,@中的所有内容都被删除。

我已经使用此代码进行了测试,但其不完整且无效。它使用ID而不是CLASS:

var datetime = document.getElementById('test').innerHTML;
var date = datetime.substr(0, datetime.indexOf('@')).trim();      
var reverse = date.split(" ");
reverse.reverse();
var result = (reverse[0] + ' ' + reverse[1])
console.log(result);

跨度可能会有所不同

感谢您的帮助:)

3 个答案:

答案 0 :(得分:2)

需要使用$.each()来改善代码行数: -

&#13;
&#13;
$(document).ready(function(){
  $('.test').each(function(){
    var spantext = $(this).html().split(" ").slice(0,2).reverse();
    $(this).html(spantext[0] + ' ' + spantext[1]);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="test">word1 word2 @ different content</span>
<span class="test">word3 word4 @ different content</span>
<span class="test">example54 example98 @ different content</span>
<span class="test">word13 word92 @ different content</span>
<span class="test">word223 word14 @ different content</span>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

实现这一目标的最简单方法是通过空格split()文本,获取结果数组的前两个元素,反转它们,然后将它们连接在一起,形成一个字符串,如下所示: / p>

&#13;
&#13;
$('.test').text(function(i, t) {
  return t.trim().split(' ').slice(0, 2).reverse().join(' ');
})
&#13;
span { display: block; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="test">word1 word2 @ different content</span>
<span class="test">word3 word4 @ different content</span>
<span class="test">example54 example98 @ different content</span>
<span class="test">word13 word92 @ different content</span>
<span class="test">word223 word14 @ different content</span>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

顺便说一下Rory的回答是为了简洁。

好吧,在jquery你可以这样做:

$(".test").each(
    function(index) {
    var text = $(this).html();
    text = text.split('@')[0].split(' ').reverse().join(' ');
    $(this).html(text);
  }
);

JS在这里:https://jsfiddle.net/q2xc1c0b/3/