首页 > 解决方案 > 如何使用 dojo 从 innerText 或 InnerHTML 获取字符数?

问题描述

我必须Dojo在我的应用程序中使用,我试图在一个元素中获取总数HTML,但我一直收到错误消息。

这是我的代码:

var attributeIcons = dojo.query(".attribute-icon");
if (attributeIcons.innerText.length = 4) {
  console.log(attributeIcons);
}

我也尝试使用这种方法:

var attributeIcons = document.getElementsByClassName("attribute-icon").innerHTML.length;
console.log(attributeIcons);

每种方法都给我同样的错误:

Uncaught TypeError: Cannot read property 'length' of undefined

标签: javascripthtmldojoinnerhtml

解决方案


dojo.query() 和 document.getElementsByClassName() 都返回一个类似数组的对象。这意味着你不能在节点数组上调用 .innerHTML(你得到未定义的),随后你也不能调用 .length。

查看这两个参考: https://dojotoolkit.org/reference-guide/1.7/dojo/query.htmlhttps://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

尝试运行以下命令以查看您的阵列。

var attributeIcons = dojo.query(".attribute-icon");
console.log(attributeIcons)

// or 

var attributeIcons = document.getElementsByClassName("attribute-icon");
console.log(attributeIcons)

您可以选择其中一个数组项,然后在其上运行 .innerHTML.length,而不是在整个数组上运行。

var attributeIcons = dojo.query(".attribute-icon");
console.log(attributeIcons[0].innerHTML.length)

// or 

var attributeIcons = document.getElementsByClassName("attribute-icon");
console.log(attributeIcons[0].innerHTML.length)

希望有帮助!


推荐阅读