用javascript中的修改值替换html内容

时间:2014-07-11 09:21:53

标签: javascript html replace

我需要一些专家意见。

我正在处理的项目是用HTML生成的报告。 我需要使用javascript来  1.找到一个数字并提取其中的一部分  2.递增/递减提取的部分
 3.用新值替换数字
 4.替换其他元素

此外,我使用的html没有标签或ID,所以我不得不抓住整个内容。

以下是我目前的情况:http://jsfiddle.net/y6Hy7/3/

var els = document.getElementsByTagName("*");
for(var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  var txt = els[i].textContent; //grabbing the text
  var patt = /\d+(?=,[0-9]{3}\sPARTS)/g; //regex pattern only grab the first 2 digits
  var res = patt.exec(txt); //execute regex on text
  if (res !== null) { //see if its not null
    var toNum = parseInt(res,10) +10;
  } //convert to int and add some fixed value
  el.innerHTML = el.innerHTML.replace(patt, toNum); //replace the original
  el.innerHTML = el.innerHTML.replace("text need to be changed and looped", "replaced");
}

它可以工作,但是不断增加被替换的值太多次了。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

仅查找p标签不是全部

喜欢

var els = document.getElementsByTagName("p");
for(var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  var txt = els[i].textContent; //grabbing the text
  var patt = /\d+(?=,[0-9]{3}\sPARTS)/g; //regex pattern
  var res = patt.exec(txt); //execute regex on text
    if (res !== null) { //see if its not null
    var toNum = parseInt(res,10) +10; } //convert to int and add 10
 el.innerHTML = el.innerHTML.replace(patt, toNum); //replace the original
 el.innerHTML = el.innerHTML.replace("text need to be changed and looped", "replaced");

  }

如果您使用TagName找到所有元素(&#34; *&#34;)。 els数组看起来像

[html, head, meta, title, script, link, style, script, body, p, p, p, p, p]

所以循环执行了14次。

如果你仍然想使用它收集所有元素并从中删除前9个元素。

var els = document.getElementsByTagName("*");
els.splice(0,9)
alert(els);

现在els只包含剩余的元素。

Fiddle