【问题标题】:Problem With Coded JavaScript Won't Replace Element After 3 Clicks单击 3 次后,编码 JavaScript 的问题不会替换元素
【发布时间】: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") 寻找&lt;data-ad-slot&gt;
  • 谢谢!可能忽略了那个。如果代码有更多问题,请赐教,因为我对javascript没有经验
  • 我已经更新了代码,使其更具可读性,哈哈。
  • 您不需要Array.from... 代码。只需ins1.click(callback);

标签: javascript jquery html css replace


【解决方案1】:

您缺少let callback = function() {... 的右大括号。另外,elem 是一个 jQuery 对象,而不是 DOM 元素,所以你不能使用parentNode。 jQuery 有一个replaceWith() 方法,可以用来直接替换元素。

function replaceAfter3Clicks(elem, newElem) {
  let count = parseInt(sessionStorage.getItem("ins_count") || "0");
  let callback = function() {
    count++;
    sessionStorage.setItem("ins_count", count);
    if (count >= 3) {
      elem.replaceWith(newElem);
    }
  }
  ins1.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>
<div><ins data-ad-slot="4092520690">ins</ins></div>

【讨论】:

  • 太棒了!谢谢你帮助我。现在,是否有可能使 sessionStorage 也可以使用。因此网络服务器会记住更改并且不会返回到其默认状态。无论是在数据库中还是在 Cookie、sessionStorage、localStorage 中。
  • 是的,每次增加计数时,您都可以执行sessionStorage.set("ins_count", count);。并初始化let count = parseInt(sessionStorage.get("ins_count") || "0")
  • 我按照您的建议更改了这些行,但它似乎不起作用。您能否使用 sessionStorage 分配更新您的帖子,以获得更多详细信息。也许,我就是想不通。
  • 我把函数名弄错了,它们是getItemsetItem。我已经更新了答案。
  • 似乎还有一些错误。 Uncaught SecurityError: Failed to read the 'sessionStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag."
猜你喜欢
  • 2020-01-15
  • 2020-01-16
  • 2020-01-06
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 2018-11-30
  • 1970-01-01
  • 2016-11-07
相关资源
最近更新 更多