Add CSS class based on ID

微笑、不失礼 提交于 2019-12-25 02:25:49

问题


I wonder how I can add a CSS class to a link based on the ID in the link, with jQuery. I wan't to add the CSS class "active" to the link if the if-statement is true. Not that I dont want to remove "pFavorite" from class in link if the statement is true, I just want to add active to, like this class="pFavorite active" Im not that in to jQuery yet. I hope my code still explains what I want to achieve.

<?php
foreach($statement as $p)
{
    if(array_search($p['id'], explode(",", $_COOKIE['cookie'])))
    {
    ?>
    <script type="text/javascript">
        $("#<?php echo $p['id']; ?>", ".pFavorite").addClass("active");
    </script>
    <a href="#" class="pFavorite" id="<?php echo $p['id']; ?>">IMG HERE</a>
<?php 
    } 
}
?>

回答1:


First of all your jQuery selector is wrong, you probably meant something similar to

$("#<?php echo $p['id']; ?>.pFavorite").addClass("active");

The above will match the element with the specific id and the class pFavorite, while your original selector would match all elements with the class pFavorite and then look for the element with the specified id inside any of those, not finding anything (because the target element is one of those having the class, not a descendant).

Second, you don't need a class selector since you are already using an id selector and ids are meant to be unique. So that would be further simplified to

$("#<?php echo $p['id']; ?>").addClass("active");

Finally: why do you want to set the class after the page loads with jQuery, when you have all the information you need on the PHP side? You can simply do

if(array_search($p['id'], explode(",", $_COOKIE['cookie']))) {
    // Use htmlspecialchars for all HTML output; you may need to specify
    // additional parameters (see the function documentation)
    printf('<a href="#" class="active pFavorite" id="%s">IMG HERE</a>',
           htmlspecialchars($p['id']));
}



回答2:


Why not:

<?php
foreach($statement as $p) {
    if(array_search($p['id'], explode(",", $_COOKIE['cookie']))) {
        echo('<a href="#" class="pFavorite active" id="' . $p['id'] . '">IMG HERE</a>');
    } 
}
?>

?




回答3:


<?php
foreach($statement as $p)
{
    if(array_search($p['id'], explode(",", $_COOKIE['cookie'])))
    {
    ?>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#<?php echo $p['id']; ?>.pFavorite").addClass("active");
        });
    </script>
    <a href="#" class="pFavorite" id="<?php echo $p['id']; ?>">IMG HERE</a>
<?php 
    } 
}
?>


来源:https://stackoverflow.com/questions/10158211/add-css-class-based-on-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!