开发者

Javascript Adding

Ok so I have columns I want added together if there is any information in them. So say I have

  • Accounts

    • 1
    • 2
    • 3
    • .

There are 4 account spaces but only 3 acco开发者_开发问答unts. How do I create java script to add this up.


Live Example

HTML:

<ul>
    <li id="accounts">
        <p> Accounts </p>
        <ul>
            <li> 1 </li>
            <li> 2 </li>
            <li> 3 </li>
            <li> . </li>
        </ul>
    </li>
</ul>

JavaScript:

// Get accounts, ul and set sum to 0
var acc = document.getElementById("accounts"),
    ul = acc.getElementsByTagName("ul")[0],
    sum = 0;

// Filter out text nodes. Returning an array of <LI> elements
var lis = Array.prototype.filter.call(ul.childNodes, function(li) {
    if (li.tagName === "LI") {
        return true;
    }
});

// Loop through LIs adding up the sum
for (var i = 0, ii = lis.length; i < ii; i++) {
    // If it's the last LI element then set the textContent.
    if (i === ii - 1) {
        lis[i].textContent = sum;
    } else {
        sum += +lis[i].textContent;
    }
}

Disclaimer: Requires Modern Browser or Modernizr.


If your real markup is a list like that, you could do something like this:

// using jquery syntax for brevity; consider it pseudocode

var jList = $('#accounts');

function addColumns() {
  var iSum = 0;
  jList.find('li').each(function() {
    var jLI = $(this);
    if(parseFloat(jLI.text()) != 'NaN')
      iSum += parseFloat(jLI.text());
  });
  return iSum;
}

This isn't super-great code. If you give us a little more info about what you're working with, something a little more robust should suggest itself. But the basic idea is that you check a set of elements-of-interest to see if they have summable content (i.e. if their text content can be interpreted as a number); then you add the summable items together.

The requirements of an algorithm like that will impose constraints on the way your "columns" can be marked-up. But there's a near-infinite set of possibilities.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜