免责声明:我是一个 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/