gpt4 book ai didi

javascript - 字数统计书签

转载 作者:行者123 更新时间:2023-12-02 19:17:22 25 4
gpt4 key购买 nike

我正在尝试在不加载外部文件的情况下创建字数统计(适用于任何页面)书签。简而言之,我想单击小书签,然后能够拖动并选择屏幕上的文本,并获得包含所选单词数的警报。我已将其放在一起以获得正确的功能,但在转换为书签时遇到了困难:

<html>
<body onmouseup="countWords()">
<article id="page1">
<h1>Home 2</h1>
<p>Welcome 2</p>
<script type="text/javascript">
function countWords() {
var selectedText = document.activeElement;
var selection = selectedText.value.substring(selectedText.selectionStart, selectedText.selectionEnd);
words = selection.match(/[^\s]+/g).length;
if (words !== "") {
alert(words);
}
}
</script>
<div><textarea></textarea></div>
</article>
</body>
</html>

第一个问题:我可能找错了树,但我想将 onmouseup 附加到 activeElement,但我不知道如何做到这一点。

第二个问题:我可以在不使用外部文件的情况下将其插入书签吗?

任何帮助将不胜感激。

最好,

塔姆勒

转义字符...这就是问题所在。

这是一个工作示例:

<a href="javascript:(document.onmouseup=function(){var selectedText=document.activeElement;var selection=selectedText.value.substring(selectedText.selectionStart,selectedText.selectionEnd);words=selection.match(/[^\s]+/g).length;if(words!==&quot;&quot;){alert(words)}})();" target="_blank">Word Count</a>

最佳答案

试试这个,看起来你的代码有点复杂:

alert(window.getSelection().toString().match(/\w+/g).length);

第一部分,window.getSelection().toString()将获取实际选定的文本。最后一部分是一个基本的正则表达式,用于匹配每个单词,然后计算匹配次数。您可以修改正则表达式以或多或少地宽松以满足您的需求。

这将简单地提醒已经选择的单词数量,如果您想在点击小书签后进行选择,您可以将上面的内容包装在监听窗口 mouseup 事件的函数中。

编辑:这是一个成熟的示例书签:

<a href="javascript: _wcHandler = function() { var _wcSelection, _wcCount; ((_wcSelection = window.getSelection().toString().match(/[^\s]+/g)) && (_wcCount = _wcSelection.length) && (window.removeEventListener('mouseup', _wcHandler) || alert(_wcSelection.length))); }; window.addEventListener('mouseup', _wcHandler);">Word Count</a>

...并以可读格式编写:

_wcHandler = function() {
var _wcSelection, _wcCount;
((_wcSelection = window.getSelection().toString().match(/[^\s]+/g))
&& (_wcCount = _wcSelection.length)
&& (window.removeEventListener('mouseup', _wcHandler)
|| alert(_wcCount)));
};
window.addEventListener('mouseup', _wcHandler);​

最后,一个 jsFiddle 供您修改:http://jsfiddle.net/Rr2KU/1/

关于javascript - 字数统计书签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12975054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com