Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

javascript - jQuery-line $(this).nextAll('.toggled:first') works in Stack Snippet and JSFiddle, but not on site

I can't figure out why the following code doesn't work on my site, but works great on JSFiddle, as well as here in a Stack Snippet:

(function($) {
  $(document).ready(function() {
    $
    $(".toggler").click(function() {
      $(this).next().slideToggle("slow");
    }).next().hide();
    $(".togglerLink").click(function() {
      $(this).nextAll('.toggled:first').fadeIn("fast");
    });
  });
})(jQuery)
.toggler {
  color: orange;
  text-decoration: underline
}
.toggler:hover {
  color: orange;
  cursor: pointer;
  text-decoration: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The <a class="togglerLink" href="#link">link</a> here, has a destination inside the Toggler.
<br>
<br>

<p class="toggler">Toggle here.</p>
<div class="toggled">In JSFIddle, or in a Stack Snippet (SO), this code is working fine. Even when the Toggler is closed, the link automatically opens the Toggle that contains it destination. --- So, then what could be going wrong, implementing this into a website?
  <br>
  <br><span id="link" style="color:green">Link-destination.</span>
  <hr>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The nextAll() function only checks for elements on the same or deeper node-level in the DOM.

So your code will work with the following HTML structure:

The <a class="togglerLink" href="#link">link</a> here, has a destination inside the Toggler.
<div class="toggled">
    <span id="link" style="color:green">Link-destination.</span>
</div>

But not with something like this:

<div>
    The <a class="togglerLink" href="#link">link</a> here, has a destination inside the Toggler.
</div>
<div class="toggled">
    <span id="link" style="color:green">Link-destination.</span>
</div>

The solution is to have a more specific selector in your jQuery code:

$(".togglerLink").click(function() {
    var id = $(this).attr('href'); // will return '#link', which we can use as ID selector
    $(id).parents('.toggled').fadeIn("fast"); // The $(id) will select the element with ID 'link' and the 'parents()' will select the parent(s) with class 'toggled'.
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...