javascript - 用于替换网页中单词的用户脚本

标签 javascript userscripts

免责声明:我是一个 JS SCSS ,我真的一点也不知道,如果这真的是一个菜鸟问题,我很抱歉。

我发现了一个用户脚本,可以让您替换网页上的单词/短语。 但是,我在第 57 行遇到一个错误,指出“需要一个条件表达式,但看到了一个赋值”

该行是:

for (i = 0; text = texts.snapshotItem(i); i += 1) {

整个脚本:

(function () { 'use strict';
var words = {
    'test 1':'test 2',
    'bleh': 'blah'
};

var regexs = [],
    replacements = [],
    tagsWhitelist = ['PRE', 'BLOCKQUOTE', 'CODE', 'INPUT', 'BUTTON', 'TEXTAREA'],
    rIsRegexp = /^\/(.+)\/([gim]+)?$/,
    word, text, texts, i, userRegexp;

// prepareRegex by JoeSimmons
// used to take a string and ready it for use in new RegExp()
function prepareRegex (string) {
    return string.replace (/([\[\]\^\&\$\.\(\)\?\/\\\+\{\}\|])/g, '\\$1');
}

// function to decide whether a parent tag will have its text replaced or not
function isTagOk (tag) {
    return tagsWhitelist.indexOf (tag) === -1;
}

delete words['']; // so the user can add each entry ending with a comma,
// I put an extra empty key/value pair in the object.
// so we need to remove it before continuing

// convert the 'words' JSON object to an Array
for (word in words) {
    if (typeof word === 'string' && words.hasOwnProperty (word) ) {
        userRegexp = word.match (rIsRegexp);

        // add the search/needle/query
        if (userRegexp) {
            regexs.push (
                new RegExp (userRegexp[1], 'g')
            );
        }
        else {
            regexs.push (
                new RegExp (prepareRegex (word)
                    .replace (/\\?\*/g, function (fullMatch) {
                        return fullMatch === '\\*' ? '*' : '[^ ]*';
                    } ),
                    'g'
                )
            );
        }

        // add the replacement
        replacements.push(words[word]);
    }
}

// do the replacement
texts = document.evaluate ('//body//text()[ normalize-space(.) != "" ]', document, null, 6, null);
for (i = 0; text = texts.snapshotItem (i); i += 1) {
    if (isTagOk (text.parentNode.tagName) ) {
        regexs.forEach (function (value, index) {
            text.data = text.data.replace (value, replacements[index]);
        } );
    }
}
} () );

有人可以解释一下这是什么意思(我喜欢理解我在做什么),以及如何解决这个问题?

最佳答案

=是一个赋值运算符。

赋值在此上下文中无效,因为 for 循环需要一个条件。

您需要使用比较运算符,例如 == , <=>=

一个可能的解决方法是:

for (i = 0; text = texts.snapshotItem(i); i += 1) {

for (i = 0; text == texts.snapshotItem(i); i += 1) {

关于javascript - 用于替换网页中单词的用户脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45945281/

相关文章:

javascript - 如何自定义警告框的位置

javascript - 我正在使用 AutoIt V3 编写脚本,但在检查元素时找不到 "object name"

javascript - 在页面加载动画上制作 css 的正确方法是什么?

google-chrome - 如何为 Chrome Tampermonkey 用户脚本创建工具栏按钮?

javascript - 禁用 window.onbeforeunload 的用户脚本

javascript - 使用JavaScript动态更改YouTube播放器的大小?

javascript - 如何从移动浏览器启动应用程序(facebook/twitter/等),但如果未安装应用程序则退回到超链接

javascript - 如何使用 Javascript 删除数组中单词之间的空格?

javascript - 在 Tampermonkey 中获取跨度文本的值

javascript - 当您不知道正在触发什么事件时,如何在更改输入字段的值后触发点击/更改事件