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

Adding a value by JavaScript inside a ins tag multiple time

我有这个代码~

<!-- 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,它将 return 一个列表。

<!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>