gpt4 book ai didi

javascript - 在 jquery 中获取 span 标签的前 2 个和后 2 个词

转载 作者:行者123 更新时间:2023-11-30 12:34:40 24 4
gpt4 key购买 nike

data-color="red"我想要 span 标签前后的 2 个词。
这是我的 html 代码:

<p>This pathway has an inner and an outer wall. The pressure <span data-color="red" class="highlight">inside the</span> eye closes the tunnel.</p>

我想要这样的输出=>

The pressure <span data-color="red" class="highlight">inside the</span> eye closes

注意:span 标签中的属性发生变化

最佳答案

您可以获取 .highlight 元素的上一个和下一个兄弟元素并对文本节点进行切片:

function get(el, dir) {
var ps = el[dir === 'prev' ? 'previousSibling' : 'nextSibling'];
if (!ps || ps.nodeType !== 3) return '';
var arr = ps.nodeValue.trim().split(/\s+/g);
return dir == 'prev'
? arr.slice(-2).join(' ')
: arr.slice(0, 2).join(' ');
}

$('p').has('.highlight').html(function () {
var e = $('.highlight', this).get(0);
return get(e, 'prev') + ' ' + e.outerHTML + ' ' + get(e, 'next');
});

http://jsfiddle.net/kzx6zhkg/

关于javascript - 在 jquery 中获取 span 标签的前 2 个和后 2 个词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26447910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com