2015-03-02 1 views
0

У меня есть группа .post divs, которые получают класс .displayOnly, когда пользователь хочет смотреть только истории с этим тегом. Я хочу показать сообщение для каждого сообщения с классом «.displayOnly», который я показываю, который отображает номер индекса + 1 в сообщении. Идея заключается в том, что сообщение скажет что-то об аффекте «Отображение 1 из 3», «Отображение 2 из 3» и т. Д. Я попытался использовать функцию index() для этого, но я получаю тот же результат для каждого сообщения, которое отображается «1 из 3».Показатель index() для класса div

Я включил свой код ниже. Может ли кто-нибудь сказать мне, где я ошибаюсь?

$('h4').click(function() { 
    var numItems = $('.displayOnly').length; 
    var currentItem = $('.displayOnly').index() + 1; 

    if ($('.displayOnly').length > 0) { 
     $("p.itemCount").css('cssText', 'display:block;'); 
     $("p.itemCount").append("Displaying " + currentItem + " of " + numItems + "."); 

    } else { 
     $("p.itemCount").css('cssText', 'display:none;'); 
     $("p.itemCount").empty(); 
    } 
}); 

UPDATE: Вот пример HTML-скрипт ссылается. Если он способен определить length(), я не уверен, почему index (this) не работает.

<div class="post urbanwildliferefuges displayOnly"> 
 
<p class="date">Tuesday, Feb 24, 2015 - 6:17 PM EST</p> 
 
<h1>Urban Refuges Make it Easier for All People to Get their ‘Nature Fix’</h1> 
 
<p>Debbie Pike is the Visitors Services Manager for Northern New Mexico National Wildlife Refuge Complex (<a href="http://www.fws.gov/refuge/las_vegas/" target="_blank">Las Vegas</a>, <a href="http://www.fws.gov/refuge/rio_mora/" target="_blank">Rio Mora</a> and <a href="http://www.fws.gov/refuge/maxwell/" target="_blank">Maxwell</a> National Wildlife Refuges). “I work with a ‘high energy’ Friends group that&#8230;<a href="http://www.fws.gov/news/blog/index.cfm/2015/1/16/Urban-Refuges-Make-it-Easier-for-All-People-to-Get-their-Nature-Fix" target="_blank">Read more here&#160;&#187;</a> <br/></p> <a href="http://americaswild.tumblr.com/post/111992041452/urban-refuges-make-it-easier-for-all-people-to-get"> 
 
</a><br /> 
 
<h4>#urbanwildliferefuges &raquo;<br /><span style="font-weight:300; font-style:italic; font-size:.85em !important;">See more like this</span></h4> 
 
<p class="itemCount"></p> 
 
<div style="float:none; clear:both;">&nbsp;</div> 
 
<hr /> 
 
</div> 
 

 
<div class="post urbanwildliferefuges displayOnly"> 
 
<p class="date">Tuesday, Feb 24, 2015 - 6:12 PM EST</p> 
 
<h1>Connection with Nature Can Happen Anywhere, Even in a City</h1> 
 
<p>Georgia Basso is a wildlife biologist in our <a href="http://www.fws.gov/northeast/ecologicalservices/coastal.html" target="_blank">Coastal Program</a> and the Service’s liaison to the <a href="http://longislandsoundstudy.net/" target="_blank">Long Island Sound Study</a>, an EPA National Estuary Program to restore and protect&#8230;<a href="http://www.fws.gov/news/blog/index.cfm/2015/1/12/Connection-with-Nature-Can-Happen-Anywhere-Even-in-a-City" target="_blank">Read more here&#160;&#187; </a><br/></p> <a href="http://americaswild.tumblr.com/post/111991702182/connection-with-nature-can-happen-anywhere-even"> 
 
</a><br /> 
 
<h4>#urbanwildliferefuges &raquo;<br /><span style="font-weight:300; font-style:italic; font-size:.85em !important;">See more like this</span></h4> 
 
<p class="itemCount"></p> 
 
<div style="float:none; clear:both;">&nbsp;</div> 
 
<hr /> 
 
</div> 
 

 
<div class="post "> 
 
<p class="date">Tuesday, Feb 24, 2015 - 6:06 PM EST</p> 
 
<h1>Secretary Talking about the Urban Wildlife Refuge Program</h1> 
 
<figure class="tmblr-embed" data-provider="youtube" data-orig-width="540" data-orig-height="304" data-url="http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6PaoZViLBPc%26list%3DUUMqPAPfBGsDMs2UiD-5Tbbg"><iframe width="500" height="281" id="youtube_iframe" src="https://www.youtube.com/embed/6PaoZViLBPc?feature=oembed&amp;enablejsapi=1&amp;origin=https://safe.txmblr.com&amp;wmode=opaque" frameborder="0" allowfullscreen=""></iframe></figure> <a href="http://americaswild.tumblr.com/post/111991188777/secretary-talking-about-the-urban-wildlife-refuge"> 
 
</a><br /> 
 
<h4># &raquo;<br /><span style="font-weight:300; font-style:italic; font-size:.85em !important;">See more like this</span></h4> 
 
<p class="itemCount"></p> 
 
<div style="float:none; clear:both;">&nbsp;</div> 
 
<hr /> 
 
</div> 
 

 
<div class="post urbanwildliferefuges displayOnly"> 
 
<p class="date">Tuesday, Feb 24, 2015 - 6:05 PM EST</p> 
 
<h1>14 URBAN WILDLIFE REFUGE PARTNERSHIPS</h1> 
 
<p>From Albuquerque to Yonkers and many cities in between, theU.S. Fish and Wildlife Service is spreading its conservation message. <a href="http://www.fws.gov/refuges/RefugeUpdate/NovDec_2014/14_urban.html" target="_blank">Click here to read more&#160;&#187;</a></p> <a href="http://americaswild.tumblr.com/post/111991128157/14-urban-wildlife-refuge-partnerships"> 
 
</a><br /> 
 
<h4>#urbanwildliferefuges &raquo;<br /><span style="font-weight:300; font-style:italic; font-size:.85em !important;">See more like this</span></h4> 
 
<p class="itemCount"></p> 
 
<div style="float:none; clear:both;">&nbsp;</div> 
 
<hr /> 
 
</div>

+0

От Jquery документы: 'Если аргумент не передается методу .index(), возвращаемое значение представляет собой целое число, указывающее положение первого элемента внутри JQuery объекта относительно его sibling elements.' so 'var currentItem = $ ('. displayOnly'). index() + 1;' всегда 1. – albciff

+0

Из jquery docs ..... .index() в этом примере они используют .. . $ ("div") .index (это); Попробуйте добавить ключевое слово это между скобками. – floor

+0

'$ (". DisplayOnly "). Index (this) + 1' – adeneo

ответ

1

Вы не устанавливая currentItem индексу элемента, который был щелкнули, вы устанавливаете его в индекс первого элемента, соответствующего селектора .displayOnly. Чтобы обратиться к объекту мероприятия, используйте $(this). А так как класс displayOnly находится на содержащем DIV, используйте .closest(), чтобы найти его.

$(this).closest('div').index('.displayOnly'); 

И так как есть более .itemCount элемент в каждом DIV, вы должны использовать .find() выбрать только один в том же DIV.

$('.displayOnly h4').click(function() { 
 
    var numItems = $('.displayOnly').length; 
 
    var curDiv = $(this).closest('div.displayOnly'); 
 
    var currentItem = curDiv.index('.displayOnly') + 1; 
 

 
    if (numItems > 0) { 
 
    curDiv.find("p.itemCount").show().html("Displaying " + currentItem + " of " + numItems + "."); 
 
    } else { 
 
    curDiv.find("p.itemCount").hide().empty(); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="post urbanwildliferefuges displayOnly"> 
 
    <p class="date">Tuesday, Feb 24, 2015 - 6:17 PM EST</p> 
 
    <h1>Urban Refuges Make it Easier for All People to Get their ‘Nature Fix’</h1> 
 
    <p>Debbie Pike is the Visitors Services Manager for Northern New Mexico National Wildlife Refuge Complex (<a href="http://www.fws.gov/refuge/las_vegas/" target="_blank">Las Vegas</a>, <a href="http://www.fws.gov/refuge/rio_mora/" target="_blank">Rio Mora</a> and 
 
    <a 
 
    href="http://www.fws.gov/refuge/maxwell/" target="_blank">Maxwell</a>National Wildlife Refuges). “I work with a ‘high energy’ Friends group that&#8230;<a href="http://www.fws.gov/news/blog/index.cfm/2015/1/16/Urban-Refuges-Make-it-Easier-for-All-People-to-Get-their-Nature-Fix" target="_blank">Read more here&#160;&#187;</a> 
 
     <br/> 
 
    </p> 
 
    <a href="http://americaswild.tumblr.com/post/111992041452/urban-refuges-make-it-easier-for-all-people-to-get"> 
 
    </a> 
 
    <br /> 
 
    <h4>#urbanwildliferefuges &raquo;<br /><span style="font-weight:300; font-style:italic; font-size:.85em !important;">See more like this</span></h4> 
 
    <p class="itemCount"></p> 
 
    <div style="float:none; clear:both;">&nbsp;</div> 
 
    <hr /> 
 
</div> 
 

 
<div class="post urbanwildliferefuges displayOnly"> 
 
    <p class="date">Tuesday, Feb 24, 2015 - 6:12 PM EST</p> 
 
    <h1>Connection with Nature Can Happen Anywhere, Even in a City</h1> 
 
    <p>Georgia Basso is a wildlife biologist in our <a href="http://www.fws.gov/northeast/ecologicalservices/coastal.html" target="_blank">Coastal Program</a> and the Service’s liaison to the <a href="http://longislandsoundstudy.net/" target="_blank">Long Island Sound Study</a>, 
 
    an EPA National Estuary Program to restore and protect&#8230;<a href="http://www.fws.gov/news/blog/index.cfm/2015/1/12/Connection-with-Nature-Can-Happen-Anywhere-Even-in-a-City" target="_blank">Read more here&#160;&#187; </a> 
 
    <br/> 
 
    </p> 
 
    <a href="http://americaswild.tumblr.com/post/111991702182/connection-with-nature-can-happen-anywhere-even"> 
 
    </a> 
 
    <br /> 
 
    <h4>#urbanwildliferefuges &raquo;<br /><span style="font-weight:300; font-style:italic; font-size:.85em !important;">See more like this</span></h4> 
 
    <p class="itemCount"></p> 
 
    <div style="float:none; clear:both;">&nbsp;</div> 
 
    <hr /> 
 
</div> 
 

 
<div class="post "> 
 
    <p class="date">Tuesday, Feb 24, 2015 - 6:06 PM EST</p> 
 
    <h1>Secretary Talking about the Urban Wildlife Refuge Program</h1> 
 
    <figure class="tmblr-embed" data-provider="youtube" data-orig-width="540" data-orig-height="304" data-url="http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6PaoZViLBPc%26list%3DUUMqPAPfBGsDMs2UiD-5Tbbg"> 
 
    <iframe width="500" height="281" id="youtube_iframe" src="https://www.youtube.com/embed/6PaoZViLBPc?feature=oembed&amp;enablejsapi=1&amp;origin=https://safe.txmblr.com&amp;wmode=opaque" frameborder="0" allowfullscreen=""></iframe> 
 
    </figure> 
 
    <a href="http://americaswild.tumblr.com/post/111991188777/secretary-talking-about-the-urban-wildlife-refuge"> 
 
    </a> 
 
    <br /> 
 
    <h4># &raquo;<br /><span style="font-weight:300; font-style:italic; font-size:.85em !important;">See more like this</span></h4> 
 
    <p class="itemCount"></p> 
 
    <div style="float:none; clear:both;">&nbsp;</div> 
 
    <hr /> 
 
</div> 
 

 
<div class="post urbanwildliferefuges displayOnly"> 
 
    <p class="date">Tuesday, Feb 24, 2015 - 6:05 PM EST</p> 
 
    <h1>14 URBAN WILDLIFE REFUGE PARTNERSHIPS</h1> 
 
    <p>From Albuquerque to Yonkers and many cities in between, theU.S. Fish and Wildlife Service is spreading its conservation message. <a href="http://www.fws.gov/refuges/RefugeUpdate/NovDec_2014/14_urban.html" target="_blank">Click here to read more&#160;&#187;</a> 
 
    </p> 
 
    <a href="http://americaswild.tumblr.com/post/111991128157/14-urban-wildlife-refuge-partnerships"> 
 
    </a> 
 
    <br /> 
 
    <h4>#urbanwildliferefuges &raquo;<br /><span style="font-weight:300; font-style:italic; font-size:.85em !important;">See more like this</span></h4> 
 
    <p class="itemCount"></p> 
 
    <div style="float:none; clear:both;">&nbsp;</div> 
 
    <hr /> 
 
</div>

+0

Возможно, вы замените 'append' на' html'. Во всяком случае, это вариация вашего решения, которое у меня было :) – Tyblitz

+0

Я действительно не потрудился исправить другие возможные ошибки в его коде. – Barmar

+0

У меня есть $ (this) .index ('. DisplayOnly'); а также $ (". displayOnly"). index (this) + 1, и я получаю результат «Отображение 0 из 3» для каждого из сообщений. Не уверен, что мне не хватает. Я включу html, на который ссылается выше. – shepherdMan1016

Смежные вопросы