获取所选/高亮显示的DIV的所有ID

Get all IDs of selected/highlighted DIVs

本文关键字:DIV ID 高亮 获取 显示      更新时间:2023-09-26

我可能正朝着完全错误的方向努力,所以我想寻求帮助。

背景/概述

我需要显示一段文本,并允许用户从该段中选择一个或多个单词,并将突出显示的文本保存到数据库中,仅用于他们的个人资料。事实上,文本的选择最终将(1)与突出显示AND(2)链接到另一段中的另一组突出显示文本(基本上,我将一个来源的短语与参考来源联系起来)

我尝试过的

我试着将段落中的每个单词放入一个DIV(和一个唯一的ID)中,每个DIV都设置为向左浮动,这样显示就可以了。

<style>
div { float: left}
</style>

而且。。。使用一个示例:

<div id="GEN_1_1">
  <div id="GEN_1_1_1">In</div>
  <div id="GEN_1_1_2">the</div>
  <div id="GEN_1_1_3">beginning</div> 
  <div id="GEN_1_1_4">God</div> 
  <div id="GEN_1_1_5">created</div> 
  <div id="GEN_1_1_6">the</div> 
  <div id="GEN_1_1_7">heaven</div> 
  <div id="GEN_1_1_8">and</div> 
  <div id="GEN_1_1_9">the</div> 
  <div id="GEN_1_1_10">earth</div>.
</div>

这看起来像是:一开始上帝创造了天地(减去粗体)

到目前为止,我已经使用

 window.getSelection()

函数来确定/抓取已高亮显示的单词。

然后我尝试使用这个:

if (window.getSelection) 
{ 
  selected_len = window.getSelection().toString().length;
  if (window.getSelection().toString().length>0) 
  { 
    div_id = window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode.id; 
  } 
}

要获得所选每个DIV的ID,但是我现在只返回一个DIV ID。

帮助请求

有没有一种巧妙的方法可以获得每个选定DIV的ID并将其放入数组,这样我就可以构造一个SQL查询将其放入数据库(查询很容易)?所选单词的总数可能达到几百个,如果不是一千个的话,所以我需要确保该解决方案能够使用大量的所选单词。

更新:JSFIDDLE演示

我再次修改了代码。看看它现在是否适合你。

$(document).ready(function () {
$(document).on('mouseup keyup', '.checked', function () {
    console.log(window.getSelection());
    if (window.getSelection().toString().length>0) {
        var count = window.getSelection();
        var arr = [];
        $('.checked span').each(function(){
            var span  = $(this)[0];
            var isT = window.getSelection().containsNode(span, true);
            if(isT){
                arr.push($(this).attr('id'));
            }
        });
        console.log(arr,count.toString());
        alert(arr);
        alert(count.toString());
       }
    });
});

我创造了一把小提琴来解决问题。点击此处查看:http://jsfiddle.net/lotusgodkk/GCu2D/18/

此外,我使用span而不是div进行文本选择。我希望这不会成为你的问题。因此,代码可以按照您的意愿工作。它将返回选中文本的父跨度的id。您可以修改它以将ID保存到数组中,也可以根据需要进行修改。

$(document).ready(function () {
$(document).on('mouseup', '.checked', function () {
    if (window.getSelection) {
        var i = getSelectionParentElement();
        console.log(i);
        alert('parent selected:  ' + i.id);
    }
});
});
function getSelectionParentElement() {
    var parent = null, selection;
    if (window.getSelection) {
        selection = window.getSelection();
       if (selection.rangeCount) {
           parent = selection.getRangeAt(0).commonAncestorContainer;
         if (parent.nodeType != 1) {
             parent = parent.parentNode;
          }
        }
    } else if ((selection = document.selection) && selection.type != "Control") {
    parent = selection.createRange().parentElement();
   }
 return parent;
}