【发布时间】:2020-01-09 18:09:24
【问题描述】:
一段时间以来一直在编写这个 javascript 代码是为了手动替换 adsense 代码,当用户点击广告 3 次时,adsense 广告会将其 data-ad-slot="4092520690" 值替换为 data-ad-slot="9092520690"。到目前为止,我已经编写了一些关于如何使用 JavaScript 代码实现这一点的步骤,但它似乎无缘无故地无法正常工作。这是元素,我正在尝试触发<ins data-ad-slot="4092520690">ins</ins>上的javascript代码
这是我迄今为止编写的代码,如果有人能为我解惑,我将不胜感激:
function replaceAfter3Clicks(elem, newElem) {
let count = 0;
let callback = function() {
count++;
if (count === 3) {
elem.parentNode.replaceChild(newElem, elem);
}
Array.from(ins1).forEach(element => {
element.addEventListener('click', callback);
});
}
const ins1 = $("ins[data-ad-slot]");
// pre-made second div for future replacement
const ins2 = document.createElement('ins');
ins2.param = '9020596432';
ins2.innerText = 'ins2';
replaceAfter3Clicks(ins1, ins2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ins data-ad-slot="4092520690">ins</ins>
【问题讨论】:
-
$("data-ad-slot")应该是$("ins[data-ad-slot]") -
$("data-ad-slot")寻找<data-ad-slot> -
谢谢!可能忽略了那个。如果代码有更多问题,请赐教,因为我对javascript没有经验
-
我已经更新了代码,使其更具可读性,哈哈。
-
您不需要
Array.from...代码。只需ins1.click(callback);
标签: javascript jquery html css replace