2015-05-29 68 views
3

我想使用jQuery打開和關閉div。 但是因爲我使用的代碼是動態的,並且會在彼此之下重複,所以我需要使用動態ID。jquery使用動態編號打開div

HTML:

<div class="categoryratings-review-<?php echo $this->htmlEscape($_review->getId())?>" style="display: none;"> 
    <p>Text</p> 
</div> 

<span class="showcategoryratings" id="review-<?php echo $this->htmlEscape($_review->getId())?>"> 
    <span class="showcategoryratings-text">Per category</span> 
</span> 

我嘗試使用這個jQuery的,但我猜的PHP線不工作:

$(document).ready(function() { 
    $('#review-<?php echo $this->htmlEscape($_review->getId())?>').click(function() { 
      $('.categoryratings-review-<?php echo $this->htmlEscape($_review->getId())?>').slideToggle("fast"); 
      $(this).toggleClass('active'); 
    }); 
}); 

如何需要正確地編輯呢?

+0

你需要把你的JS代碼在PHP渲染,而不是在外部文件中的HTML。 – lmgonzalves

回答

3

您可以在Javascript中不使用PHP。

$(document).ready(function() { 
    $('.showcategoryratings').click(function() { 
     var categoryId = $(this).attr('id').split('-')[1]; 

     $('.categoryratings-review-'+categoryId).slideToggle("fast"); 
     $(this).toggleClass('active'); 
    }); 
}); 

我認爲它的工作原理。

1

如果你把你的元素分組如下,它會更容易。通過這樣做,您根本不需要ID。看一看。

$(document).ready(function() { 
 
    $('.showcategoryratings').on("click", function() { 
 
     $(this).closest(".group").find(".categoryratings-review").slideToggle("fast"); 
 
     $(this).toggleClass('active'); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="group"> 
 
    <div class="categoryratings-review" style="display: none;"> 
 
     <p>Text1</p> 
 
    </div> 
 
    
 
    <span class="showcategoryratings"> 
 
     <span class="showcategoryratings-text">Per category1</span> 
 
    </span> 
 
</div> 
 

 
<div class="group"> 
 
    <div class="categoryratings-review" style="display: none;"> 
 
     <p>Text2</p> 
 
    </div> 
 
    
 
    <span class="showcategoryratings"> 
 
     <span class="showcategoryratings-text">Per category2</span> 
 
    </span> 
 
</div> 
 

 
<div class="group"> 
 
    <div class="categoryratings-review" style="display: none;"> 
 
     <p>Text3</p> 
 
    </div> 
 
    
 
    <span class="showcategoryratings"> 
 
     <span class="showcategoryratings-text">Per category3</span> 
 
    </span> 
 
</div>

0

你可幫了所有的ID與review-開始響應

$('[id^="review-"]').click(function() { 

    $('.categoryratings-' + $(this).attr('id')).slideToggle('fast') ; 

    $(this).toggleClass('active'); 

});