开发者

$(element:visible) before or after $(this)

How do I determine if $(element:visible) is placed before or after $(this) in HTML?

My HTML code looks like this

<div class="wrapper" style="display:none;">
    <div class="title">1</div>
    <div class="text">Lorem Ipsum</div>
</div>

<div class="wrapper">
    <div class="title">2</div>
    <div class="text">Lorem Ipsum</div>
</div>

<div class="wrapper" style="display:none;">
    <div class="title">3</div>
开发者_如何转开发    <div class="text">Lorem Ipsum</div>
</div>

<div class="wrapper" style="display:none;">
    <div class="title">4</div>
    <div class="text">Lorem Ipsum</div>
</div>

When I click on title 2 I want to know if there is visible $('.wrapper') before that title.


I hope this is what you need

$(".title").click(function(){
  if($(this).parent().prev().is(":visible")) alert("Previous is visible!")
});

This tells you if the previous .wrapper (previous to clicked title) is visible.

EDIT: This solves your updated question

$(".title").click(function(){
  if($(this).parent().prevAll(".wrapper").is(":visible")) alert("Previous is visible!")
});

Hope this helps. Cheers


To sum it up. You need to check if there are any visible elements with class "wrapper" prior to clicked element.

If that is it, this should do it.

$(".wrapper").click(function() {
  var el;
  el = $(this);
  $(".wrapper:visible").each(function(index) {
    if ( el.get(0) === $(this).get(0) ) {
      alert("There are no visible wrappers prior to this one.");
      return false;
    } else {
      alert("There are visible wrappers prior to this one.");
      return false;
    }
  });
});

Or:

$(".wrapper").click(function() {
  if ( $(this).prevAll(".wrapper:visible").length ) {
    return alert("There is " + $(this).prevAll(".wrapper:visible").length  + " wrappers prior to this one.");
  } else {
    return alert("There are no visible wrappers prior to this one.");
  }
});


$(this).parent("div:visible")

This will give you a parent only if it is visible.


$(this).closest('.wrapper').prev().is(':visible');

Will get the closest parent with a class wrapper meaning even if $(this) is deeper inside the wrapper it will still function properly.


If you are looking to see if there is ANY previous visible wrappers... $(this).parent().prev(".wrapper:visible").length()

If you are looking to see if only the previous one before it is visible... $(this).parent().prev().is(":visible")


$('.title').click(function() {
    if ($(this).parent().prev('.wrapper:visible').length) {
        console.log('visible');
    } else {
        console.log('not visible');
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜