如果页面是 index.php 使用 jQuery 添加 class 到 header
Add class to header if page is index.php using jQuery
使用 jQuery,我只想在 index.php
上向 <header>
标签添加 class
伪代码:
var page_name = get current page name
if
$page_name == 'index.php'
then
add 'is_index' class to <header>
else
do nothing
我只想在索引页上对 header 设置不同的样式,因此我试图插入一个选择器以使用 CSS 抓取。我可以在PHP中实现,但是我找不到jQuery使用什么功能。我需要使用 jQuery 因为 <header>
可能已经有一个 class 我不相信 PHP 可以添加到一个已经有 class 的元素(但是也许我错了)。
简单
$('header').toggleClass('is_index', /\/index.php$/.test(location.pathname))
注意: 这将在 all <header>
元素上切换 class 如果您有多个元素.
toggleClass()
的文档在这里 ~ http://api.jquery.com/toggleclass/#toggleClass-className-state
此外,在PHP
中这样做应该没有问题
<?php $isIndex = basename(__FILE__) == 'index.php';
// or however you determine you're on index.php
?>
<header class="whatever <?= $isIndex ? 'is_index' : '' ?>">
使用 jQuery,我只想在 index.php
上向<header>
标签添加 class
伪代码:
var page_name = get current page name
if
$page_name == 'index.php'
then
add 'is_index' class to <header>
else
do nothing
我只想在索引页上对 header 设置不同的样式,因此我试图插入一个选择器以使用 CSS 抓取。我可以在PHP中实现,但是我找不到jQuery使用什么功能。我需要使用 jQuery 因为 <header>
可能已经有一个 class 我不相信 PHP 可以添加到一个已经有 class 的元素(但是也许我错了)。
简单
$('header').toggleClass('is_index', /\/index.php$/.test(location.pathname))
注意: 这将在 all <header>
元素上切换 class 如果您有多个元素.
toggleClass()
的文档在这里 ~ http://api.jquery.com/toggleclass/#toggleClass-className-state
此外,在PHP
中这样做应该没有问题<?php $isIndex = basename(__FILE__) == 'index.php';
// or however you determine you're on index.php
?>
<header class="whatever <?= $isIndex ? 'is_index' : '' ?>">