简体   繁体   中英

With Javascript, how to read what is within <span> tags, when the value is created by Javascript

I have this code and I basically want it to read what is created in between the <span> tags (that value is created by another javascript script), and then take that to display 'article' or 'articles'.

<span id="quantity" class="simpleCart_quantity"></span>

<script type="text/javascript">
var q = document.getElementById('quantity');

if (q == 1) {
    document.write("article");
}
else
  {
  document.write("articles");
  }
</script> 

So I want it to check <span id="quantity" class="simpleCart_quantity"></span> , and if the value that is present is '1', write 'article' and if the value is '0' or more than '1' write 'articles'. I hope you can get it.

Now it works, but only if you actually write something in between the <span> , like: 1

But the value is created externally and the script must be able to read the value that is created when the page is loaded right?

The result should be a sentence that says 'You have x article(s) in your shopping cart'.

I have no idea of how I should do this, I hope somebody can help me.

Thanks a lot!

<span id="quantity" class="simpleCart_quantity"></span>
<!-- ... --->
<span id="quantityText"></span>

<script type="text/javascript">
    var quantity = document.getElementById("quantity"),
        quantityText = document.getElementById("quantityText");

    if (parseInt(quantity.innerHTML, 10) === 1) {
        quantityText.innerHTML = "article";
    } else {
        quantityText.innerHTML = "articles";
    }
</script> 

Note that you must use a radix argument (10, in this case) to make sure numbers are interpreted as base10. Otherwise everything starting with '0x' would be interpreted as hexadecimal (base16), for example.

alternative syntax using the ternary operator :

<script type="text/javascript">
    var quantity = document.getElementById("quantity"),
        quantityText = document.getElementById("quantityText"),
        quantityValue = parseInt(quantity.innerHTML, 10);

    quantityText.innerHTML = "article" + (quantityValue === 1 ? "" : "s");
</script> 

In addition to pure javascript, you can also use jQuery:

   jQuery($this).find('span.simpleCart_quantity') // find the span with class name: simpleCart_quantity
   .text() // get the text

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