使用 javascript 抓取所选内容周围的单词以及同一
的一部分元素?
我正在创建一个书签,它接受选定的单词和同一段落元素中的其他单词,对它们进行编码,然后将它们发送到我的服务器。
例如,考虑以下情况:
<p>The quick brown fox jumped over the fence.</p>
如果用户选择“jumped”(通过突出显示它)并单击小书签,我希望将“jumped”作为一个编码字符串发送,并将“The Quick Brown Fox Jumped over the fence”作为附加内容发送编码的字符串。
这是我到目前为止所得到的。 getSelection 函数将“跳转”发送到我的服务:
javascript:location.href='http://www.myservice.com/new.php?'+'url_def='+encodeURIComponent(getSelection())
我可以在此附加什么才能将段落元素中的附加文本发送到我的服务?
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:location.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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你所拥有的在 IE 中不起作用,IE 有不同的机制来获取选择。如果您想要的是包含整个选择的元素的文本,您可以执行类似的操作,这将适用于所有主要浏览器。
示例: http://jsfiddle.net/timdown/X7n5R/
代码:
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:
您可以使用
document.getSelection()
并检查锚节点以查看已选择哪个。
所以这将引用“周围文本”:
document.getSelection().anchorNode.parentNode.innerHTML
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