【问题标题】:Javascript find a position of a word in a string containing HTMLJavascript 在包含 HTML 的字符串中查找单词的位置
【发布时间】:2017-06-06 17:01:50
【问题描述】:

我得到了以下 HTML:

<div id="editable_phrase">
   My 
   <span style="background-color: #19FC49;"> first</span> 
   <span style="background-color: #09AC20;"> first</span> //note 2 firsts here
   <span style="background-color: #D2C3EA;"> phrase</span>
</div>

原来的短语是-我的第一句话

我需要在我的原始短语中找到所选单词的第一个字母的位置。因此,如果我选择(用鼠标突出显示)phrase,我需要得到 10(或任何值)。我尝试使用 charAt()window.getSelection 但仍然得到错误的结果。

此外,如果我选择相同的单词但在不同的位置(例如我上面的示例,其中有 2 个 first 单词),我会得到相同的结果,因为它找到了第一个单词的位置,而我需要第二个单词.

我可以使用 jQuery。任何想法都会受到欢迎。谢谢你。

【问题讨论】:

  • This sounds like an X Y problem,你想对那个职位做什么?
  • 我需要将它存储在数据库中,然后将 标签应用于整个单词以突出显示
  • 如果你在两个元素之间突出显示呢? (例如上例中的“st phra”)
  • 我已经实现了一个将所选内容捕捉到单词的功能,但无论如何如果我能在没有它的情况下获得字母的位置,那就太好了
  • @Masha 我已经删除了我的答案。稍后当我有更多时间时,我将不得不对其进行更多研究。重要的部分是突出显示文本的代码。这是解决该问题的问题:stackoverflow.com/questions/3731328/…

标签: javascript jquery html


【解决方案1】:

正如您所说,您已经有了一个选择单词的函数,就像indexOf() 一样简单 - 只需将下面的selectedText 替换为您的函数返回的单词,然后在文本之后执行操作被选中:

let el = document.getElementById('editable_phrase');

let selectedText = "phrase";
let originalPhrase = el.innerText;

console.log(originalPhrase.indexOf(selectedText));
<div id="editable_phrase">
  My
  <span style="background-color: #19FC49;"> first</span>
  <span style="background-color: #D2C3EA;"> phrase</span>
</div>

【讨论】:

  • 在这种情况下看起来innerTexttextContent 更好。
  • 它不需要您在答案中的替换.. @JosephMarikle。您的答案是一个很好的答案,但请随意窃取 innerText。 :-)
【解决方案2】:

这是一个结合baao's answerJoseph Marikle's answer的答案(已被删除)。

selection.anchorNode.textContent 获取突出显示的单词。

$("#editable_phrase").bind('mouseup', function(e) {
  var selection;
  var selectedWordPos;
  if (window.getSelection) {
    selection = window.getSelection();
  } else if (document.selection) {
    selection = document.selection.createRange();
  }
  selectedWordPos = $("#editable_phrase").text().replace(/\s\s+/g, ' ').indexOf(selection.anchorNode.textContent.replace(/\s\s+/g, ' '));
  console.log(selectedWordPos);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editable_phrase">
  My
  <span style="background-color: #19FC49;"> first</span>
  <span style="background-color: #D2C3EA;"> phrase</span>
</div>

【讨论】:

  • 你选择的是整个单词,没关系,但是尝试选择相同的字母或添加相同的单词并检查结果是否改变
【解决方案3】:

遍历 div 的子元素,并将它们连接到一个字符串,直到达到所需的值,然后返回它的长度。 例如,像这样: var str = "";

var bool = false;
$('#editable_phrase').children().each(function(){
    if ($(this).text() == "phrase")
        bool = true;
    if (!bool)
        str+=$(this).text();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多