好吧,我已经打了一个多星期了,我受不了了。
我的目标是随机替换任何给定页面上的特定URL的HREF。
例如: https://example.com/offer/free-pizza/
我的URL版本包含要忽略的查询字符串参数,即https://example.com/offer/free-pizza/?sliceapp,这就是为什么我在此行中显式使用正则表达式为特定URL引号的原因:
str.replace(/"https:\/\/example\.com\/offer\/free-pizza\/"/g
我正在使用Google跟踪代码管理器中的自定义HTML代码来部署以下代码。不幸的是,链接不包含ID,因此我无法专门调用它们,因此我正在查看在页面主体内中包含的所有内容,换句话说,是[[,即我正在处理的每个页面的正文。一切与下面的代码完全一样,except不会出现页面上的延迟加载图像。
<script>
function myfunction(){
var str = document.getElementById("main").innerHTML;
var res = str.replace(/"https:\/\/example\.com\/offer\/free-pizza\/"/g, function() {
return ['https://example.com/somewhere-else/', 'https://example.com/offer/free-pizza/'][Math.floor(Math.random() * 2)]
return Math.floor(Math.random() * (max - min + 1)) + min;
});
document.getElementById("main").innerHTML = res;
}
</script>
从我的故障排除中,我知道问题与使用innerHTML返回整个有关。图像和返回的HTML显然不起作用。因此,我开始改为只查看页面上的各个URL,而不是整个部分,这样我就可以完全绕过图像问题。
为了完成这一点,我必须写出数十种变体,但是似乎没有任何效果。
var els = document.querySelectorAll("a[href^='https://example.com/offer/']"); for (var i = 0, l = els.length; i < l; i++) { var el = els[i]; el = el.replace(/"https:\/\/example\.com\/offer\/free-pizza\/"/g, function() { return ['https://example.com/somewhere-else/', 'https://example.com/offer/free-pizza/'][Math.floor(Math.random() * 2)] return Math.floor(Math.random() * (max - min + 1)) + min; })}; </script>
我希望有一个比我聪明的人看到我的明显缺点,并指出我的背景和目标,即如何以更有效的方式编写此代码。谢谢。
innerHTML
的问题是,您可能会删除(并替换)已将事件侦听器附加到它们的DOM节点,从而使它们无效。我猜这是惰性加载机制利用的。因此,您不必遍历整个文档的innerHTML
,只需遍历定位标记并替换href
属性:
document
.querySelectorAll("a[href^='https://example.com/offer/']")
.forEach(function (el) {
el.href = el.href.replace(/https\:\/\/example\.com\/offer\//g, replaceFn);
});
function replaceFn() {
return [
'https://example.com/somewhere-else/',
'https://example.com/offer/free-pizza/'
][Math.floor(Math.random() * 2)];
}