开发者

Use javascript to grab the words surrounding a selection and part of the same <p> element?

I'm looking to create a bookmarklet that takes a selected word and the other words in the same paragraph element, encodes them, and sends them to my server.

For instance, consider the following:

<p>The quick brown fox jumped over the fence.</p>

Had the user selected "jumped" (by highlighting it) and clicked the bookmarklet, I would want to send "jumped" as one encoded string and "The quick brown fox jumped over the fence" as an additional encoded string.

Here's what I've got thus far. The getSelection function sends "jumped" to my service:

javascript:locati开发者_Python百科on.href='http://www.myservice.com/new.php?'+'url_def='+encodeURIComponent(getSelection())

What can I append to this in order to get the additional text in the paragraph element to my service?


What you have won't work in IE, which has a different mechanism for getting hold of the selection. If what you want is the text of element containing the whole selection, you can do something like this, which will work in all major browsers.

Example: http://jsfiddle.net/timdown/X7n5R/

Code:

function getSelectedText() {
    var selectedText = "", containerText = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0);
            selectedText = range.toString();
            var container = range.commonAncestorContainer;
            if (container.nodeType == 3) {
                container = container.parentNode;
            }
            containerText = container.textContent;
        }
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        selectedText = textRange.text;
        containerText = textRange.parentElement().innerText;
    }
    return {
        selectedText: selectedText,
        containerText: containerText
    };
}


You could use document.getSelection() and check the anchorNode to see which <p> has been selected.

So This would reference to the "surrounding text": document.getSelection().anchorNode.parentNode.innerHTML

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜