5

我正在尝试为具有<h2>标签的页面上的每个元素生成一个 MD5 校验和,然后将这些值显示为弹出窗口。

我已经拥有的代码应该获取每个<h2>元素,我只需要获取每个元素的实际值。

var ghead = document.getElementsByTagName('h2');

for (i=0; i<ghead.length; i++) {
    var gh = ghead[i];
    var ts = gh.toString();
    var ms = b64_md5(ts);
    alert(ts);
    alert(ms);
}

的用法b64_md5(ts)基本上是将ts变量转换为 MD5 值。但是,ts变量是元素类型的 ID 或名称,而不是元素的值本身。

另外,如果我想创建一个 cookie,其中存储了两个值,一个名称和一个校验和,我可以gh.innerText;用来设置唯一名称,因为到目前为止我在使用这种方法时遇到了问题。

4

3 回答 3

12

您可以使用该innerHTML属性来获取元素的 HTML 内容:

var ts = gh.innerHTML;

请注意,h2元素(和大多数其他元素)没有“值”。只有充当表单控件的元素才有value属性(例如input元素)。

于 2012-07-03T12:36:51.560 回答
2

要获取 h2 标记元素 gh 的文本内容:

var text = gh.childNodes.item(0).data;
于 2012-07-03T13:07:40.203 回答
1

如果你想访问一个元素的类型,你可以要求这个:

gh.nodeName // contains the name of the node in uppercase e.g. "H2"
gh.nodeType // contains the numerical Type of the node e.g. "1"
gh.id       // contains the value of the node's id attribute
gh.name     // contains the value of the name attribute (typically for form elements)

如下所述,访问实际的节点内容是另一回事:

gh.innerHTML   // contains the full html source within the node
gh.innerText   // (IE only) contains the visible textual content stripped of any html markup
gh.textContent // W3C compliant equivalent of innerText

对于跨浏览器访问文本内容,请使用以下内容:

var text = gh.innerText || gh.textContent;
于 2012-07-03T12:49:22.213 回答