获取包含特定元素的完整单词

时间:2016-06-05 08:25:56

标签: javascript jquery

引用特定的DOM元素(例如<mark>),我们如何获得包含该元素的完整单词?

例如:

H<mark>ell</mark>o Wor<mark>l</mark>d, and He<mark>llo</mark>, <mark>Pluto</mark>!

我希望得到以下输出:

  • 首先<mark>Hello
  • 第二名:World
  • 第三名:Hello
  • 第四名:Pluto

&#13;
&#13;
var $marks = $("mark");

var tests = [
  "Hello",
  "World",
  "Hello",
  "Pluto",
];

function getFullWord($elm) {
  // TODO: How can I do this?
  // 		   This is obviously wrong.
  return $elm.html();
}

var $marks = $("mark");
tests.forEach(function(c, i) {
  var word = getFullWord($marks.eq(i));
  if (word !== c) {
    alert("Wrong result for index " + i + ". Expected: '" + c + "' but got '" + word + "'");
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
H<mark>ell</mark>o Wor<mark>l</mark>d, and He<mark>llo</mark>, <mark>Pluto</mark>!
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:5)

如果您需要快速而紧凑的代码(单行代码),请尝试以下方法:

var $marks = $('mark');

$marks.each(function() {
    var wholeWord = (this.previousSibling.nodeValue.split(' ').pop() + 
                     this.textContent + 
                     this.nextSibling.nodeValue.split(' ')[0]
                     ).replace(/[^\w\s]/gi, '');
});

JSFiddle(登录控制台和评论)