如何通过javaScript获取此锚点的父对象?
<p>Lorem Ipsum is simply dummy
text of the printing and typesetting
<a href="http://somplace.com/index.php?content=
{{in this place i want to retrieve 20 character of
the parent p}}"></a> industry.
</p>
答案 0 :(得分:2)
使用this.parentNode.innerHTML.substring(0, 20)
:
<a onclick="alert(this.parentNode.innerHTML.substring(0, 20)" ..............
下面:
this
指当前链接parentNode
指的是链接的父级,例如本案中的段落innerHTML
阅读父母的HTML substring
过去常常将字符从0增加到20。答案 1 :(得分:2)
假设您已经在名为anchorElement
的变量中引用了锚标记,您可以像这样获取父代:
var anchorParent = anchorElement.parentNode;
或者,如果您正在尝试获取对锚点的引用,您可以给它一个id并像这样执行以实际获取文本并将其放入href:
<p>Lorem Ipsum is simply dummy
text of the printing and typesetting
<a id="myAnchor" href="http://somplace.com/index.php?content=
{{in this place i want to retrieve 20 character of
the parent p}}"></a> industry.
</p>
var elem = document.getElementById("myAnchor"); // get anchor object
var parent = elem.parentNode; // get parent
var text = parent.innerHTML.substr(0,20); // get first 20 chars of text
elem.href = "http://somplace.com/index.php?content=" + text;
答案 2 :(得分:0)
我建议您添加JavaScript的基本知识,如果您偶尔使用一次,可能不需要。