简体   繁体   中英

run a javascript function for specific css .class selectors

I have a JavaScript library and it uses this function for example to convert English numbers to Persian:

persianJs("345").englishNumber().toString(); //returns: ۳۴۵

I have an html structure to show some dynamic numerical values like this:

<span class="price"><!-- price amount  --></span>

How can I run the JavaScript function in header or footer to display any price amount in Persian format?

you can use document.getElementsByClassName("price")[0].innerText

 //var pNumber =persianJs("345").englishNumber().toString(); //returns: ۳۴۵ var pNumber="۳۴۵"; document.getElementsByClassName("price")[0].innerText=pNumber;
 <span class="price"><!-- price amount --></span>

I'm not sure that I'm on the same page with you, but I think you need to specify the function that will be triggered each time when you need, and this function should query all places where you need to change the price amount.

For instance:

function updatePrice() {
   return persianJs("345").englishNumber().toString();
};

window.onload = function(){
    let elements = document.querySelectorAll('.price');
      if(elements && elements.length) {
         elements.forEach(el => el.textContent = updatePrice())
      } 
}

It's just my vision of your problem, but again I'm not sure that I correctly understand you...

The following code will convert all the .price span to english numbers on your code base.

    window.onload = function(){
      var els = document.querySelectorAll('.price');
      els.forEach(function(item) {
        item.textContent = persianJs(item.textContent).englishNumber().toString();
      });
    }

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