所以我想尝试添加一个类,但它不起作用
<script>
var url = document.location.pathname;
debugger;
if(url === '/about.php') {
$('.about').addClass('active');
//document.getElementsByClassName('about')[0].addClass('active');
console.log(url);
}
//important part start
if(url === '/index.php') {
$('.homee').addClass('active');
document.getElementsByClassName('homee')[0].addClass('active');
console.log(url);
}
//important part end
if(url === '/sch.php') {
$('.schedule').addClass('active');
//document.getElementsByClassName('schedule')[0].addClass('active');
console.log(url);
}
if(url === '/images.php') {
$('.gallery').addClass('active');
//document.getElementsByClassName('gallery')[0].addClass('active');
console.log(url);
}
if(url === '/videos.php') {
$('.gallery').addClass('active');
}
console.log(url);
</script>
<ul class="menu" >
<li class='homee' ><a href="index.php">HOME</a></li>
</ul>
你可以看到我尝试了2种方法和$(&#39; .homee&#39;)。addClass(&#39; active&#39;);没有说无法读取属性&#39; addClass&#39;未定义但它仍然没有添加类
答案 0 :(得分:2)
您在填充HTML之前运行脚本 - 在解析器到达$('.homee').addClass('active');
行时,尚未创建<li class='homee' >
,因为您可以看到,该元素在下面脚本。
将整个脚本包装在解析文档后触发的函数中:
<script>
$(function() {
var url = document.location.pathname;
debugger;
if(url === '/about.php') {
$('.about').addClass('active');
//document.getElementsByClassName('about')[0].addClass('active');
console.log(url);
}
//important part start
if(url === '/index.php') {
$('.homee').addClass('active');
document.getElementsByClassName('homee')[0].addClass('active');
console.log(url);
}
//important part end
if(url === '/sch.php') {
$('.schedule').addClass('active');
//document.getElementsByClassName('schedule')[0].addClass('active');
console.log(url);
}
if(url === '/images.php') {
$('.gallery').addClass('active');
//document.getElementsByClassName('gallery')[0].addClass('active');
console.log(url);
}
if(url === '/videos.php') {
$('.gallery').addClass('active');
}
console.log(url);
});
</script>
更好的是,将脚本放在一个单独的文件中,并为其指定defer
属性:
<script src="myscript.js" defer>
答案 1 :(得分:1)
如果要使用JQuery
,则需要包装代码(function($) {
$(document).ready(function(){
// your code here
});
})(jQuery);
答案 2 :(得分:0)
.addClass()是一个jQuery方法。如果要使用普通javaScript添加类,可以编写:
document.getElementsByClassName('homee')[0].classList.add('active')
有关文档,请参阅classList
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementsByClassName('homee')[0].classList.add('active')
});
.active {
background: red;
}
<ul class="menu" >
<li class='homee' ><a href="index.php">HOME</a></li>
</ul>