引用特定的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
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;
答案 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(登录控制台和评论)