使用动态id打开jquery div

3
我想使用jQuery打开和关闭一个div。 但是由于我使用的代码是动态的,并且将在彼此下面重复,因此我需要使用动态id。
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');
    });
});

我需要如何正确地编辑这个?

您需要将JS代码放在PHP呈现的HTML中,而不是外部文件中。 - lmgonzalves
3个回答

3
你可以在Javascript中不使用PHP来完成它。
$(document).ready(function() {
    $('.showcategoryratings').click(function() {
        var categoryId = $(this).attr('id').split('-')[1];

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

我认为它有效。


2

如果您像下面这样对元素进行分组,那么会更容易。这样做,您根本不需要使用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

你可以将所有以 review- 开头的 ID 都挂钩到响应上

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

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

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

 });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接