javascript - 使用 Jquery 即时更改 CSS 类

标签 javascript jquery css

好的,我是 Javascript 和 jqyery 菜鸟,所以寻求帮助。

我有一个 CSS 菜单栏,用作整个网站的元素。通过为 pressed 元素分配一个类,可以将单个按钮显示为已单击。我拥有的第一个链接显示为已按下。我可以在我的 View 中轻松访问 URL,因此我知道我在哪里,但我希望能够根据 url 的位置在页面加载时动态更改类,因此菜单将显示为该区域选择的内容。我在下面包含了菜单的两个元素。 我想根据变量中的值将 'class'=> 'pressed' 更改为 'class'=> ''。我该怎么做?

    <ul id="menuBar" class="topmenu">
    <input type="checkbox" id="css3menu-switcher" class="switchbox">
    <label onclick="" class="switch" for="css3menu-switcher"></label>
    <li class="topfirst">
        <?php
        echo $this->Html->link(
            $this->Html->image('icons/group.png', array('width' => '20', 'line-height' => '20'))
            . ' ' . __('Organisations'),
            array('controller' => 'organisations', 'action' => 'index'),
            array('escape' => false, 'class'=> 'pressed'));
        ?>
        <ul>
            <li> <?php
                echo $this->Html->link(
                    $this->Html->image('icons/group_add.png', array('width' => '20', 'line-height' => '20'))
                    . ' ' . __('New Organisation'),
                    array('controller' => 'organisations', 'action' => 'add'),
                    array('escape' => false));
                ?></li>
        </ul>
    </li>
    <li class="topmenu">
        <?php
        echo $this->Html->link(
            $this->Html->image('icons/telephone.png', array('width' => '20', 'line-height' => '20'))
            . ' ' . __('Contacts'),
            array('controller' => 'contacts', 'action' => 'index'),
            array('escape' => false));
        ?>
        <ul>
            <li>  <?php
                echo $this->Html->link(
                    $this->Html->image('icons/telephone_add.png', array('width' => '20', 'line-height' => '20'))
                    . ' ' . __('New contact'),
                    array('controller' => 'contacts', 'action' => 'add'),
                    array('escape' => false, 'class'=> 'unpressed'));
                ?>
        </ul>
    </li>
</ul>

以下是两种预期的 html 输出:

    <li class="topmenu">
<a href="/dev/oak/trunk/contacts">
<img width="20" alt="" line-height="20" src="/dev/oak/trunk/img/icons/telephone.png">
Contacts
</a></li>


    <li class="topmenu">
<a class='pressed' href="/dev/oak/trunk/contacts">
<img width="20" alt="" line-height="20" src="/dev/oak/trunk/img/icons/telephone.png">
Contacts
</a></li>

最佳答案

关于javascript - 使用 Jquery 即时更改 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27062140/

相关文章:

html - 导航栏损坏取决于屏幕尺寸/比例/比例

Javascript touchend 事件不会在 Android 上触发

javascript - 一个html输入类型如何调用两个函数?

javascript - 如何将变量传递给 jQuery 验证

html - CSS 不正确

html - 计算出的字体大小大于 Asus Nexus 7 上 CSS 中定义的大小

javascript - 在新选项卡中加载页面后调用函数

javascript - 如何使一个元素出现而不触发同一类的其他元素

javascript - 在 .append jquery 中循环

javascript - 具有动态填充和元素计数的 Flexbox 未正确调整大小