简体   繁体   English

使用 jQuery,如何通过选择文本获取第一个父元素?

[英]Using jQuery, how do I get the first parent element found with a selection of text?

I have the following element assigned to a variable, along with a set of selection indexes for this variable.我将以下元素分配给一个变量,以及该变量的一组选择索引。

var html_element = $("<p>Some text goes <b>here</b> then continues here</p>").appendTo("body");
var start = 15;
var end = 17;

This SHOULD represent the letters "her" in the word "here".这应该代表单词“here”中的字母“her”。 Is there any way for me to use these indexes and the html_element to get the first HTML element (parent) of the selection...?我有什么办法可以使用这些索引和 html_element 来获取选择的第一个 HTML 元素(父元素)...? So in this case I want to grab " here " as a jQuery object.所以在这种情况下,我想将“ here ”作为一个 jQuery 对象。

So that if I want I can change the text "here" to anything such as "new here".这样,如果我愿意,我可以将文本“此处”更改为诸如“新此处”之类的任何内容。

In plain terms I want to grab the first element before the start_index.简单来说,我想在 start_index 之前获取第一个元素。

Try using :contains() to select element containing characters within html_element at indexes 15 through 17 ;尝试使用:contains()选择包含html_element索引1517中字符的元素; .text() , String.prototype.slice() .text() , String.prototype.slice()

 var html_element = $("<p>Some text goes <b>here</b> then continues here</p>") .appendTo("body"); var start = 15; var end = 17; // element containing charaters at parent element text indexes 15 through 17 var selected = $(":contains(" + html_element.text().slice(15, 17) + ")" , html_element); // set `context` to `html_element` // set new text at `selected` selected.text(function(_, text) { return "new " + text });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>

alternatively, .contents() , for loops to count characters of text nodes with p element或者, .contents()for循环来计算具有p元素的文本节点的字符

 var html_element = $("<p>Some text goes <b>here</b> then continues here</p>") .appendTo("body"); var start = 15; var end = 17; var text = 0; var elem = null; var contents = html_element.contents(); for (var index = 0; index < contents.length; index++) { var el = contents[index]; if (elem === null && (el.nodeType === 3 || el.firstChild.nodeType === 3)) { var txt = el.textContent || el.nodeValue; for (var i = 0; i < txt.length; i++) { text += 1; if (text >= start + 1 && text <= end) { elem = $(el) break } }; } else { break; } }; console.log(elem, text, text >= start && text <= end); elem.text(function(_, txt) { return "new " + txt })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>

如果你只想替换<b><\\b>标签的内容,你可以这样做:

html_element.find('b').text('My custom Text');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM