2009-06-09 155 views
2

我正在开发一个Firefox扩展,用户选择一个文本,然后文本转到REST Web服务并返回一些结果。获取所选节点ID

我与文本选择的问题,我用这个方法来获取所选文本:

var selectedText = window.getSelection(); 

我得到的结果selectedText变量,并将其发送到服务器,但我不知道如何获取此节点的Id或任何内容以将结果附加到其中。

我尝试过在JavaScript和jQuery中使用Firebug和大量的Google搜索查询,但没有有用的结果!

回答

2

编辑:因为你需要这一个FF扩展,你可以跳过所有功能的IE浏览器,你需要做的一切是这样的:

window.getSelection().getRangeAt(0).commonAncestorContainer 

更多范围的信息:https://developer.mozilla.org/en/DOM/range


已经有类似的问题:

Get selected text and selected nodes on a page?

我修改的功能的位:

<script type="text/javascript"> 
    function getTextSelection() { 
    if(document.selection) 
     return document.selection; 
    else if(window.getSelection) 
     return window.getSelection(); 
    else if(document.getSelection) 
     return document.getSelection(); 
    else 
     return false; 
    } 
    function getSelectionRange() { 
    var selection = getTextSelection(); 
    if(selection.getRangeAt) 
     return selection.getRangeAt(0); 
    else if (selection.createRange) 
     return selection.createRange(); 
    else 
     return false; 
    } 
    function getSelectionParent(r) { 
    if(r.parentElement) 
     return r.parentElement; 
    else if(r.commonAncestorContainer) 
     return r.commonAncestorContainer; 
    else 
     return false; 
    } 
</script> 

HTML:

<body> 
    <p><em>This is just some random text. </em><strong>Select me and then click the button!!!</strong></p> 
    <p><input type="button" value="Parent element?" onclick="alert('The selection\'s parent element is: ' + getSelectionParent(getSelectionRange()).nodeName);" /></p> 
</body> 

我在IE6,7和FF3.0测试这些东西。工作没有任何问题。唯一必须注意的是,与FF不同的IE会忽略文本节点。

如果你想尝试一下自己:http://dev.freedig.org/files/selection.html

+0

我读它,它只是给你选定的文本不是节点,我错了吗? – 2009-06-10 05:38:39

0

使用本

<script type="text/javascript"> 
    function getTextSelection() { 
    if(document.selection) 
     return document.selection; 
    else if(window.getSelection) 
     return window.getSelection(); 
    else if(document.getSelection) 
     return document.getSelection(); 
    else 
     return false; 
    } 
    function getSelectionRange() { 
    var selection = getTextSelection(); 
    if(selection.getRangeAt) 
     return selection.getRangeAt(0); 
    else if (selection.createRange) 
     return selection.createRange(); 
    else 
     return false; 
    } 
    function getSelectionParent(r) { 
    if(r.parentElement) 
     return r.parentElement; 
    else if(r.commonAncestorContainer) 
     return r.commonAncestorContainer; 
    else 
     return false; 
    } 
</script> 

HTML:

<body> 
    <p><em>This is just some random text. </em><strong>Select me and then click the button!!!</strong></p> 
    <p><input type="button" value="Parent element?" onclick="alert('The selection\'s parent element is: ' + getSelectionParent(getSelectionRange()).nodeName);" /></p> 
</body>