javascript - 通过 JavaScript 在 ins 标签内多次添加值

标签 javascript insert variable-assignment adsense queryselector

我有这个代码~

<!-- ONE -->
    <ins class='adsbygoogle'
        style='display:block'
        data-ad-client='ca-pub-XXXXXXXXXXXXXXX'
        data-ad-format='auto'
        data-full-width-responsive='true'></ins>

<!-- TWO -->
    
    <ins class='adsbygoogle'
        style='display:block'
        data-ad-client='ca-pub-XXXXXXXXXXXXXXX'
        data-ad-format='auto'
        data-full-width-responsive='true'></ins>
(相同的代码,两次)
我用它来添加一个值“data-ad-slot=123456789”
<script> 
var x= 123456789;
var elem = document.querySelector('.adsbygoogle');
elem.dataset.adSlot = x;
console.log(elem);
</script>
但它只与第一个( <!--ONE--> )一起工作一次。如何使它与多个代码一起工作?
谢谢!

最佳答案

请试试这个,你将不得不使用 querySelectorAll,它会返回一个列表。

<!DOCTYPE html>
<html>
<head>
    <title>
    </title>
</head>
<body>
    <!-- ONE -->
    <ins class='adsbygoogle' style='display:block' data-ad-client='ca-pub-XXXXXXXXXXXXXXX' data-ad-format='auto'
        data-full-width-responsive='true'></ins>

    <!-- TWO -->
    <ins class='adsbygoogle' style='display:block' data-ad-client='ca-pub-XXXXXXXXXXXXXXX' data-ad-format='auto'
        data-full-width-responsive='true'></ins>
    <script>
        window.addEventListener('load', (event) => {
            var x = 123456789;
            var elems = document.querySelectorAll('.adsbygoogle');
            elems.forEach((elem) => {
                elem.dataset.adSlot = x;    
                console.log(elem);
            });
        });
    </script>
</body>
</html>
输出:
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-XXXXXXXXXXXXXXX" data-ad-format="auto" data-full-width-responsive="true" data-ad-slot="123456789"></ins>

<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-XXXXXXXXXXXXXXX" data-ad-format="auto" data-full-width-responsive="true" data-ad-slot="123456789"></ins>

关于javascript - 通过 JavaScript 在 ins 标签内多次添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63219586/

相关文章:

c++ - C++程序中的基本指针问题

javascript - 使用 moment.js 时丢失 "diff"值

javascript - 选择最接近克隆元素的 h2 标题

Javascript 生成的 ul 在 Internet Explorer 中看起来不同

mysql - 使用单个查询将值插入多个表

python - 如何将数据列分配给变量

c++ - boost::shared_ptr 和分配派生类

php - 使用 google geolocation api 进行地理定位

javascript - 在没有自动关闭标签的元素之前和之后插入内容

jquery - 通过使用日期(按日期)在元素之间插入元素