我试图在不加载外部文件的情况下创建单词计数(对于任何页面)bookmarklet。简而言之,我想单击书签,然后能够在屏幕上拖动和选择文本,并获得有关所选单词数的警报。我将它们放在一起以获得正确的功能,但是在转换为小书签时遇到了麻烦:

<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/

07-24 09:46
查看更多