简体   繁体   English

jQuery切换无法在PHP foreach循环中工作

[英]Jquery toggle not working in php foreach loop

I am trying to show a booking form when I click the button using jquery toggle. 我使用jQuery切换单击按钮时试图显示预订表格。

HTML 的HTML

foreach($result['apiAvailableBuses'] as $value){?>
    <tr>
</td>
        <td><?php echo $value['fare']; ?></td>
        <td>

            <?php echo $value['availableSeats'].'&nbsp;Seats'; ?>&nbsp;&nbsp;
            <input type="button" id="<?php echo $i; ?>" class="btn btn-primary" value="Book" name="Book">
        </td>
    </tr>
<tr class="main">
        <td colspan="5">
            <div class="well" id="result<?php echo $i; ?>">Booking form here</div>
        </td>
    </tr>
<?php $i++; } ?>

Script 脚本

$(".main").hide();
$(".btn-primary").click(function(){
        var id=$(this).attr('id');
        $('#result'+id).toggle();
    });

But when I click on the button I can't see the booking form div 但是当我点击按钮时,我看不到预订表格div

In your script, you are hiding the parent tr using $(".main").hide(); 在脚本中,您使用$(".main").hide();隐藏了父tr $(".main").hide(); and hence toggle of the child element is not working. 因此子元素的toggle无效。 To make it work you have to make visible the parent element and then toggle the div. 要使其工作,您必须使父元素可见,然后切换div。

$(".main").hide();
$(".btn-primary").click(function(){
       $(".main").show();
    var id=$(this).attr('id');
    $('#result'+id).toggle();
});

Now it should work. 现在应该可以了。

Try using .on() 尝试使用.on()

$(document).ready(function(){
$(document).on("click",".btn-primary",function(){
    var id=$(this).attr('id');
    $('#result'+id).toggle();
});
});

UPDATE 更新

Another thing I want to explain. 我想解释的另一件事。 You are clicking on a button and then getting its ID and then doing .toggle() with it. 您正在单击一个按钮,然后获取其ID,然后对其进行.toggle()

I think you can do this way also. 我想您也可以这样做。

$(document).ready(function(){
$(document).on("click",".btn-primary",function(){
    //var id=$(this).attr('id');
    //$('#result'+id).toggle();
    $(this).closest("tr").next("tr").find(".well").toggle();
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM