当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Trouble using .closest function

问题描述:

I'm trying to make a sidebar menu for a dashboard. I want to implement this with .closest as it will fit with my code right. Here is a simple example of what I'm trying to do: https://jsfiddle.net/eu8kjzh4/10/

Why isn't the closest span's (and the only span in this case) text being replaced with a '-'? In my code, I have

$('.' + Key).closest( '.' + Key ).css("color", "#000");

This code works just fine, but the one in the jsfiddle does not.

网友答案:

closest traverses up the DOM and is used for nested elements.

In your markup, your div is not a descendant of your span, not even a sibling.

You have 1. To retrieve the previous sibling (the first li after the body) 2. And find the span inside the li

$(document).ready(function() {
  $(".sub").prev().find('span').text('-');
});

Also, in your fiddle, you forgot to include jQuery.

Here is a working code : https://jsfiddle.net/qwc6pepr/1/

网友答案:

Incorrect function: .closest( selector ) Returns: jQuery Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree

What you want is the prev which finds the first sibling prior to the element

$(document).ready(function() {
  $('.sub').prev('li').find('span').text('-');
});
网友答案:

From jQuery documentation

Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements

Your span is neither a Parent Element of your div.sub in the DOM, nor matches with the $(".sub") rule.

The only way to make your jQuery code work with your HTML structure :

$("#plusMinus1").text("-");

Or modify your HTML structure to match with the .closest() method requierements

网友答案:

Fiddle

When you go to the parent you'll end up in the body. From there you can find the span.

$(document).ready(function() {
  $(".sub").parent().find("span").text("-");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<body>
  <li>
    <a class="selected" href="#" onclick="return false;">Dashboard 1 <span id="plusMinus1">+</span></a>
  </li>
  <div class="sub">
    <ul>
      <li><a id="s1" href="">Test A</a>
      </li>
      <li><a id="s2" href="">Test B</a>
      </li>
      <li><a id="s3" href="">Test C</a>
      </li>
    </ul>
  </div>
</body>
分享给朋友:
您可能感兴趣的文章:
随机阅读: