多次在ins标记内通过JavaScript添加值
我有这个密码~多次在ins标记内通过JavaScript添加值,javascript,insert,variable-assignment,adsense,queryselector,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 -->
<!-- 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”
var x=123456789;
var elem=document.querySelector('.adsbygoogle');
elem.dataset.adSlot=x;
控制台日志(elem);
但是第一个(
)只工作一次。如何使它与多个代码一起工作
谢谢大家! 请尝试此操作,您必须使用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>
window.addEventListener('load',(事件)=>{
var x=123456789;
var elems=document.querySelectorAll('.adsbygoogle');
要素forEach((要素)=>{
elem.dataset.adSlot=x;
控制台日志(elem);
});
});
输出:
<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>
非常感谢您,您真是太棒了!
<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>