简体   繁体   English

获取JavaScript中先前的同级锚元素的ID

[英]Get the id of previous sibling anchor element in javascript

Solved : to get the id of the previous element, use previousElementSibling.id instead of previousSibling.id . 已解决:要获取上一个元素的ID,请使用previousElementSibling.id而不是previousSibling.id Thank you to Xufox and Skyline3000 who quickly provided the solution. 感谢迅速提供解决方案的Xufox和Skyline3000。


Having some breadcrumbs done of anchors elements, I'm trying to get the id of the previous sibling when one breakcrumb is clicked (ie the parent category). 让锚元素完成一些面包屑后,我试图在单击一个碎屑(即父类别)时获取上一个兄弟的ID。 eg. 例如。 Fruits> Apples> Green apples

Unfortunately, my code does not work. 不幸的是,我的代码无法正常工作。

  • alert(this.previousSibling) returns [object Text] alert(this.previousSibling)返回[object Text]
  • alert(this.previousSibling,id) returns id is undefined . alert(this.previousSibling,id)返回id is undefined
  • alert(this.previousSibling,getAttribute(\\'id\\') returns TypeError: this.previousSibling.getAttribute is not a function . alert(this.previousSibling,getAttribute(\\'id\\')返回TypeError: this.previousSibling.getAttribute is not a function
  • alert(this.previousSibling,attr(\\'id\\')) returns TypeError: this.previousSibling.attr is not a function . alert(this.previousSibling,attr(\\'id\\'))返回TypeError: this.previousSibling.attr is not a function

I assume that the sibling is not correctly reached as I was expecting some Element or Object and not Text. 我假定未正确达到同级,因为我期望某些元素或对象而不是文本。

Here's what the HTML and javascript of two breadcrumbs look like: 这是两个面包屑的HTML和javascript外观:

<a id="n5_40_64_40" onclick="javascript:
    var tree=jQuery('#tree').dynatree('getTree');
    if (!tree.activateKey('40')) {
      var parent=0;
      if (1) {
       parent=this.previousSibling.id.split(/[_]+/).pop();
      }
    }
    return false;" href="">Apples</a>
>
<a id="n5_40_64_64" onclick="javascript:
    var tree=jQuery('#tree').dynatree('getTree');
    if (!tree.activateKey('64')) {
      var parent=0;
      if (2) {
       parent=this.previousSibling.id.split(/[_]+/).pop();
      }
    }
    return false;" href="">Green apples</a>

All text and whitespace, including whitespace and new lines between your HTML tags, count as a TextNode . 所有文本和空格(包括HTML标记之间的空格和换行符)均视为TextNode Thus the tag's previous sibling is actual the textNode of whitespace between the <a> tags. 因此,标签的先前同级实际上是<a>标签之间的空白文本节点。 What you really want to do is find the previous sibling that is an element (HTML tag). 您真正想要做的是找到先前的兄弟元素,即元素(HTML标签)。

For that you should simply use this.previousElementSibling . 为此,您应该只使用this.previousElementSibling

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM