在DOM元素上方选择注释

时间:2015-06-16 07:49:58

标签: javascript jquery

有个问题。我有这个HTML:

enter image description here

我按下一个按钮(这是' editcurrent'类),它会显示一些内容。这是有效的,但我想检查哪个注释在控件组之上,我想获得注释的值,以便我可以决定我想向用户显示什么。但是我如何得到这个值,最近或父? (我使用jQuery)

我收到了这段代码:

var comments = $('.form-horizontal').contents().filter(function(){ return this.nodeType===8; })

这给了我表格的所有评论。但我真的不知道如何使用最接近的方法来搜索评论。

console.log($(this).closest('.control-group').children(this.nodeType===8));

这显然不起作用......有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:3)

你不能使用jQuery 选择注释节点,但你可以用它来选择.control-group并从那里开始向后工作,因为评论将是它以前的兄弟(可能在那里有一个空白文本节点,具体取决于标记):

var node = $(".form-horizontal .control-group")[0];
while (node && node.nodeType != Node.COMMENT_NODE) {
  node = node.previousSibling;
}
alert(node ?  node.nodeValue : "Not found");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal">
  <fieldset>
    <!-- Form Name -->
    <legend></legend>
    <!-- Multiple Radios -->
    <div class="control-group">
      ....
    </div>
  </fieldset>
</form>