简体   繁体   中英

js : not running function for each div onload

<div onload="mkid(4)" id='bxltr'></div>
<div onload="mkid(9)" id='bxltr'></div>
<div onload="mkid(7)" id='bxltr'></div>

<script>
function mkid(itg){
    nitg=itg+455+367*674;
    document.getElementById('bxltr').innerHTML=nitg;
}
</script>

I want to get value from specific div's onload function and then return that value to its specified div, but after running this script nothing is displayed on page

  1. You cannot use onload on a div element. It will not work

  2. Id's must be unique

Try this solution, it's working as you wanted

 function mkid(){ var elements = document.getElementsByClassName('bxltr'); for(var i = 0; i< elements.length; i++) { var nitg = Number(elements[i].getAttribute("data-count")) +455+367*674; elements[i].innerHTML = nitg; } } window.onload = mkid; 
 <div data-count="4" class='bxltr'></div> <div data-count="9" class='bxltr'></div> <div data-count="7" class='bxltr'></div> 

You can use Document.querySelectorAll() with Array.prototype.forEach() and data attributes :

 document .querySelectorAll('.bxltr') .forEach(el => el.innerHTML = el.dataset.mk + 455 + 367 * 674); 
 <div data-mk="4" class="bxltr"></div> <div data-mk="9" class="bxltr"></div> <div data-mk="7" class="bxltr"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM