【问题标题】:How can i add a class to an <a> with a specific href in php?如何在 php 中将类添加到具有特定 href 的 <a> ?
【发布时间】:2017-07-31 16:36:33
【问题描述】:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$("ul").find("a[href=filename]").addClass('active');

在我的 header.php 中有一个 ul:

<li><a href="index.php">Főoldal</a></li>
<li><a href="gallery.php">Galéria</a></li>
<li><a href="games.php">Játékok</a></li>
<li><a href="contacts.php">Elérhetőségeink</a></li>
<li><a href= "about.php">Rólunk</a></li>

我花了几个小时来处理这个。根据我目前所在的网站,我只是无法将类添加到锚标记。

【问题讨论】:

  • 让我们知道console.log(filename); 的输出是什么。在var filename = url.substring(url.lastIndexOf('/')+1); 之后添加它并检查您的浏览器控制台并告诉我们
  • 执行$("ul &gt; li &gt; a[href='"+filename+"']").addClass('active') 可能会起作用,但最好在 PHP 中添加类,因为 PHP 知道它在哪个部分更准确(例如,如果您打算使用重写等)跨度>

标签: php navbar element nav


【解决方案1】:

试试这个:

$uri=$_SERVER['REQUEST_URI'];

这样你就得到了 URI,比如“/index.php”,现在你需要将它与你标签中的 url 进行比较。即使我建议使用 JS/jQuery,例如:

var current_path_url=window.location.pathname;

$('a[href="'+current_path_url+'"]').parent().addClass('active');

【讨论】:

    【解决方案2】:

    变量不会在带引号的字符串中展开,您必须使用连接(除非您想使用 ES6 模板文字,但旧版浏览器不支持它们)。

    $("ul > li > a[href=" + filename + "]").addClass('active');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 2018-07-30
      • 2012-06-18
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多