Javascript字符串未设置

时间:2017-04-03 12:01:56

标签: javascript

我有以下功能:

  contractToobar(): void {
      let extraItemsElements = document.getElementsByClassName('toolbar-open');
      if (extraItemsElements && extraItemsElements.length > 0) {
        for (let i: number = 0; i < extraItemsElements.length; i++) {
          extraItemsElements[i].className = 'xxx';
          console.log('after: ', extraItemsElements[i].className);
        }
      }
  }

我正在尝试设置extraItemsElements[i].className。但是,代码输出以下内容:

after:  toolbar toolbar-md toolbar-open toolbar-open toolbar-open toolbar-open

我希望该值为'xxx'

即。 className未设置为xxx的值。

任何建议都表示赞赏。

更新

如果我尝试以下方法:

  contractToobar(): void {
    let replacements: string[] = [];
    let extraItemsElements = document.getElementsByClassName('toolbar-open');
    if (extraItemsElements && extraItemsElements.length > 0) {
      for (let i: number = 0; i < extraItemsElements.length; i++) {
        let s: string = this.replaceAll(extraItemsElements[i].className, ' toolbar-open', '');
        replacements[1] = s;
      }
    }
    for (let i: number = 0; i < replacements.length; i++) {
      extraItemsElements[i].className = replacements[i];
      console.log('after: ', extraItemsElements[i].className);
    }
  }

  replaceAll(str, find, replace): string {
    let returnValue: string = str.replace(new RegExp(find, 'g'), replace);
    return returnValue;
  }

我明白了:

  

无法设置属性&#39; className&#39;未定义的

2 个答案:

答案 0 :(得分:0)

不确定replaceAll的作用,它应该是

&#13;
&#13;
function replaceAll(reg,input,replace) {
 return input.replace(reg, function(match){
  return replace
 })
}

var r = replaceAll(/ toolbar-open/g, 'toolbar toolbar-md toolbar-open toolbar-open toolbar-open toolbar-open', '')

console.log(r)
&#13;
&#13;
&#13;

答案 1 :(得分:0)

感谢georg的评论,以下作品:

  contractToobar(): void {
    let replacements: string[] = [];
    let extraItemsElements = document.getElementsByClassName('toolbar-open');
    if (extraItemsElements && extraItemsElements.length > 0) {
      for (let i: number = 0; i < extraItemsElements.length; i++) {
        let s: string = this.replaceAll(extraItemsElements[i].className, ' toolbar-open', '');
        replacements[1] = s;
      }
    }
    for (let i: number = 0; i < replacements.length; i++) {
      if (extraItemsElements && extraItemsElements[i] && extraItemsElements[i].className) {
        extraItemsElements[i].className = replacements[i];
      }
    }
  }

  replaceAll(str, find, replace): string {
    let returnValue: string = str.replace(new RegExp(find, 'g'), replace);
    return returnValue;
  }``