使用 JavaScript 获取 <h2> 标签的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11311033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the value of an <h2> tag with JavaScript
提问by JamEngulfer
I am trying to generate an MD5 check-sum of every element on a page that has the <h2>
tag, then display the values as a popup.
我正在尝试为具有该<h2>
标记的页面上的每个元素生成 MD5 校验和,然后将这些值显示为弹出窗口。
The code I have already should get each <h2>
element, I just need to get the actual value of each one.
我已经拥有的代码应该获取每个<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);
}
The usage of b64_md5(ts)
basically is what converts the ts
variable into the MD5 value. However, the ts
variable is the ID or name of the Type of Element, not the Element's value itself.
的用法b64_md5(ts)
是将ts
变量转换成MD5值。但是,ts
变量是元素类型的 ID 或名称,而不是元素的值本身。
Also, if I wanted to make a cookie that has two values stored in it, a name and a checksum, could I use gh.innerText;
to set the unique name, as I have had issues with using this method so far.
此外,如果我想制作一个存储有两个值的 cookie,一个名称和一个校验和,我可以gh.innerText;
用来设置唯一名称,因为到目前为止我在使用这种方法时遇到了问题。
回答by James Allardice
You can use the innerHTML
property to get the HTML contents of an element:
您可以使用该innerHTML
属性来获取元素的 HTML 内容:
var ts = gh.innerHTML;
Note that h2
elements (and most other elements) don't have a "value". Only elements that behave as form controls have a value
property (e.g. the input
element).
请注意,h2
元素(和大多数其他元素)没有“值”。只有作为表单控件value
的input
元素才有属性(例如元素)。
回答by Torsten Walter
If you want to access the type of an element you can just ask for this:
如果你想访问一个元素的类型,你可以这样要求:
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)
As mentioned below, accessing the actual node content is a different matter:
如下所述,访问实际节点内容是另一回事:
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
For cross browser access to the text contents use something like this:
要跨浏览器访问文本内容,请使用以下内容:
var text = gh.innerText || gh.textContent;
回答by Michael Besteck
To get the textual content of a h2 tag element gh:
要获取 h2 标签元素 gh 的文本内容:
var text = gh.childNodes.item(0).data;