【问题标题】:Javascript add class active when click a link after load another page?加载另一个页面后单击链接时,Javascript添加类活动?
【发布时间】:2018-09-18 17:32:36
【问题描述】:

我有一个列表a.href 到许多包含电影的 URL。 当我点击a.href 时,它会重新加载我的页面。我不知道如何将.active 类添加到当前选择的a.href

在 Ajax 调用中,就像这段代码一样简单,它可以正常工作,因为页面没有重新加载。但我写在 PHP 上并使用 $_GET$_POST 方法。所以必须重新加载页面。

有什么方法可以在a.href 上添加类.active 链接被点击了吗?

<div class="btn-group listEp col-md-12">
    $i = 0;
    <a href="#" style="opacity: 1;" class="btn btn-success disabled">Episode:</a>
    <?php foreach($data['episodes'] as $epList) { ?>
        <a class="btn btn-default" href="<?php echo $epList['href']); ?>"> <?php echo $i++; ?> </a>
    <?php } ?>
</div>
$(function() {
    $('#listEp').on("click", "a", function() {  
        $( "#listEp a:first-child" ).css("cssText", "background: #4CAF50 !important;");
        $(this).addClass('active').siblings().removeClass('active');
    });
});

【问题讨论】:

  • 一集的href是什么样的,$epList['href']的值是多少?通常这样的事情会起作用:&lt;a class="btn btn-default &lt;? if($ifActive) {echo "active";} ?&gt;" href="...你只需要找到一种方法来检查它是否处于活动状态,可能通过比较$_GET$epList['href']

标签: javascript php css


【解决方案1】:

如果您不想在点击后重新加载页面并为此创建自定义操作,请执行以下操作:

$('#listEp').on("click", "a", function(e) {  
    e.preventDefault() // this will disable default action which is redirect in case of a element
    e.stopPropagation() // this will stop element beeing propagated by other functions

    $( "#listEp a:first-child" ).css("cssText", "background: #4CAF50 !important;");
    $(this).addClass('active').siblings().removeClass('active');
}); 

【讨论】:

  • 不,点击后必须重新加载页面。您的解决方案不起作用,因为它获取了 a.href 的 URL 并进行了更改。
【解决方案2】:

您的目标似乎是一个不存在的 ID,该元素有一个类 listEp。改用$('.listEp')

【讨论】:

    【解决方案3】:

    你可以这样做,

    $('a.btn[href]').click(function(){
        $('a.btn[href]').removeClass('active');
        $(this).addClass('active');
    });
    

    上面的代码从其他相同元素中删除活动类并在该元素中添加类。 将以下代码添加到重新加载时呈现的页面,

    $(document).ready(function(){
        $('a.active.btn[href]').removeClass('active');
    });
    

    【讨论】:

    • 新页面加载后,这个添加的类active不会消失吗?
    • 一个index.php文件中的所有代码。我在 index.php 文件中添加了您的代码,但没有任何变化。
    猜你喜欢
    • 2011-10-26
    • 2018-08-11
    • 2011-01-03
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    相关资源
    最近更新 更多