【问题标题】:Need Help Replacing Specific Paramater For Element需要帮助替换元素的特定参数
【发布时间】:2019-09-07 01:38:55
【问题描述】:

最近,我一直在使用 javascript 代码来替换被点击 3 次的元素,而我的问题是,我也无法替换 data-id-slot-"" 参数。对于这个元素<ins data-ad-slot="4092520690">ins</ins>。我所管理的只是单击 3 次后替换 innerText 。

function replaceAfter3Clicks(elem, newElem) {
  let count = 0;
  let callback = function() {
    count++;
    if (count >= 3) {           
      elem.replaceWith(newElem);
    }
  }
  ins1.click(callback);
}

const ins1 = $("ins[data-ad-slot]");

// pre-made second ins for future replacement
const ins2 = document.createElement('ins');
ins2.?? = '9020596432';
ins2.innerText = 'ins2';

replaceAfter3Clicks(ins1, ins2);

【问题讨论】:

    标签: javascript jquery html css parameters


    【解决方案1】:

    我认为您对 HTML 属性和 javascript 对象属性之间的区别感到困惑

    ins2.?? = '9020596432';
    

    我认为你想要更多这样的东西

    ins2.setAttribute("data-id-slot", "9020596432")
    

    https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

    【讨论】:

      【解决方案2】:

      您正在谈论元素的attribute。可以通过元素的setAttribute方法设置元素的属性。

      const ins2 = document.createElement('ins');
      ins2.setAttribute('data-ad-slot', '9020596432');
      ins2.innerText = 'ins2';
      

      【讨论】:

        【解决方案3】:

        由于这是data- attribute,您可以使用dataset property 访问它。

        function replaceAfter3Clicks(elem, newElem) {
          let count = 0;
          let callback = function() {
            count++;
            if (count >= 3) {           
              elem.replaceWith(newElem);
            }
          };
          ins1.click(callback);
        }
        
        const ins1 = $("ins[data-ad-slot]");
        
        // pre-made second ins for future replacement
        const ins2 = document.createElement('ins');
        ins2.dataset.adSlot = '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="">Placeholder</ins>

        正如其他答案所建议的那样,您也可以使用setAttribute,但dataset 更短,在我看来更简洁。

        ins2.dataset.adSlot = '9020596432';
        // vs
        ins2.setAttribute('data-ad-slot', '9020596432');
        

        【讨论】:

          猜你喜欢
          • 2016-01-29
          • 1970-01-01
          • 2022-12-09
          • 2017-08-31
          • 2016-06-24
          • 2014-03-08
          • 2018-05-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多