有人能帮我找到我的代码的问题吗?我试图将li
设置为基于它的url激活。但问题是加载后没有设置为活动。给我一些关于如何做这件事或其他方法的想法?
$subj_descr
有空格,COMPUTER PROGRAMMING 1
, ENGLISH 2
这是我的php代码,li
和a
找到。
<li data-popover="true" rel="popover" data-placement="right"><a href="#" data-target=".premium-menu" class="nav-header collapsed" data-toggle="collapse"><i class="fa fa-fw fa-book"></i> Lectures<i class="fa fa-collapse"></i></a></li>
<li><ul id="wa" class="premium-menu nav nav-list collapse in">
<?php
$sql ="SELECT enroll_ref FROM std_enrolled WHERE stud_no = '$stud_no'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)){
$enroll_ref = $row['enroll_ref'];
}
$sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$enroll_ref'";
$results = mysqli_query($con, $sql3);
while($row = mysqli_fetch_array($results)){
$subj_descr = $row['subj_descr'];
?>
<li id="<?php echo $subj_descr; ?>" ><a href="viewlecture.php?subjdescr=<?php echo $subj_descr;?>"><span class="fa fa-caret-right"></span><?php echo ucwords(strtolower($subj_descr)); ?></a></li>
<?php
}
?>
</ul></li>
这是我的js
$(document).ready(function() {
$(function(){
var current = location.pathname;
$('#wa li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
});
你可以试试下面的代码:
$(document).ready(function() {
$(function(){
//location.search will give us query string i.e. part present after ? mark and ? itself which is nothing but ?subjdescr=COMPUTER PROGRAMMING 1
var current = decodeURIComponent(location.search); //decodeURIComponent to decode white space chars like %20 will get converted to white space
alert(current);
$('#wa li a').each(function(){
var $this = $(this);
alert(decodeURIComponent($this.attr('href')));
// if the current path is like this link, make it active
if(decodeURIComponent($this.attr('href')).indexOf(current) !== -1){
$this.closest("li").addClass('active'); //setting the active class to parent li and not to a tag
}
})
})
});
我猜你需要将active
设置为li
标签而不是<a>
所以只需通过$.closest()
抓取它
注意:添加decodeURIComponent()
以避免字符串比较中的编码字符
请尝试。
将location.pathname
替换为window.location.href
$(document).ready(function() {
$(function(){
var current = window.location.href;
$('#wa li').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if(current.indexOf($this.find('a').attr('href')) !== -1){
$this.addClass('active');
}
})
})
});
你可以用它来查找URL中的文本
var my_url = "localhost/studentportal/viewlecture.php?subjdescr=COMPUTER%20PROGRAMMING%202";
var found_my_url = my_url.search("viewlecture.php");
var found_hashed = my_url.search("\?");
if(found_my_url!=-1 && found_hashed!=-1)
{
var url_split = my_url.split("?");
var url_final = url_split[1].split("=");
if(url_final[1]=="COMPUTER%20PROGRAMMING%202")
{
alert("Found in the URL");
}
else
{
alert("NOT FOUND in the URL");
}
}