簡體   English   中英

使用for循環識別html .classes(jQuery)

[英]using a for loop to identify html .classes (jQuery)

我正在使用simplepie引入兩個RSS提要。 然后使用PHP foreach循環, echo顯每個提要帖子包含在.story_overview類中的.story_overview ,並為每篇文章添加.pin類。 我在PHP foreach使用jQuery來hide.story_overview並在.story_overview和相應的.pin類的末尾添加一個唯一的標識號,這是.pin

<script>
    $('.story_overview').hide();
    $('.pin').attr('class','pin' + i);
    $('.story_overview').attr('class','story_overview' + i);   
    i++;
</script>

我正在嘗試將.pin懸停在.pin顯示各自的.story_overview因此.pin1會顯示.story_overview1 )以達到預期的結果。 我目前正在嘗試使用JavaScript for循環來執行此操作,但它拒絕工作:

<script>
    for (x = 0; x <= i; x++){
        $('.pin'+ x.toString()).mouseover(function(){
            $('.story_overview' + x.toString()).show();
        });

        $('.pin'+ x.toString()).mouseout(function(){
            $('.story_overview' + x.toString()).hide();
        }); 
    };
</script>

我已經嘗試了所有jQuery命令,方法是嘗試相同的代碼,但在類名的末尾使用標識號( 而不是x.toString ),並將代碼放置在for循環之外,並且一切正常。

任何幫助將不勝感激! 提前致謝。

您可以簡單地做到這一點:

  $('.pin').mouseover(function(){
            $('.story_overview').eq($(this).index()).show();
   }).mouseout(function(){
            $('.story_overview').eq($(this).index()).hide();
   }); 

您可以通過將.eq()方法與.index()來獲取懸停元素的索引,從而獲得所需的輸出。

或者您可能會這樣:

  $('.pin').mouseover(function(){
            $('.story_overview'+$(this).index()).show();
   }).mouseout(function(){
            $('.story_overview'+$(this).index()).hide();
   }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM