HTML代码:
<ul class="nav nav-tabs">
<li role="presentation" id="tab1" class="active"><a onclick="switchTabs(1)">Tab1</a></li>
<li role="presentation" id="tab2"><a onclick="switchTabs(2)">Tab2</a></li>
</ul>
JS代码:单击时未发生错误,但未进行切换
function switchTabs(idx) {
// this is not working
var $li = $(this).parent();
if($li.hasClass('active')) {
return false; // not enter here
}
$li.removeClass('active');
if (idx === 1) {
$li.next().addClass('active');
} else {
$li.prev().addClass('active');
}
// but this works while using id selector
/*if (idx === 1) {
$("#tab1").addClass('active');
$("#tab2").removeClass('active');
} else if(idx === 2) {
$("#tab2").addClass('active');
$("#tab1").removeClass('active');
}*/
return false;
}
可能是什么原因?
答案 0 :(得分:3)
尝试这种方法,我认为这将是针对您情况的更好解决方案
<html>
<head>
<meta charset="utf-8"/>
</head>
<style>
.active {
color: red;
}
</style>
<body>
<ul class="nav nav-tabs">
<li role="presentation" id="tab1" class="active"><a onclick="switchTabs(this)">Tab1</a></li>
<li role="presentation" id="tab2"><a onclick="switchTabs(this)">Tab2</a></li>
</ul>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script>
function switchTabs(elm) {
var $li = $(elm).parent();
if(!$li.hasClass('active')) {
$li.addClass('active');
$li.siblings().removeClass('active');
}
}
</script>
答案 1 :(得分:2)
将元素发送到函数中,然后您将其作为父元素:
<a onclick="switchTabs(this,1)">
然后
function switchTabs(elm,idx) {
// this is not working
var $li = $(elm).parent();
// Rest of your code...
答案 2 :(得分:0)
选中此方法可以使其变得更容易(并使用$(this)
)
$(document).on('click','.nav li a', function(){
let tab = $(this).data('tab');//$(this) is the a clicked.
$('.nav li.active').removeClass('active');//hide active Tab
$('.nav li#tab'+tab).addClass('active');//show Tab
})
.active{font-size:20px;color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav nav-tabs">
<li role="presentation" id="tab1" class="active"><a data-tab="1">Tab1</a></li>
<li role="presentation" id="tab2"><a data-tab="2">Tab2</a></li>
</ul>
答案 3 :(得分:0)
您仅将索引而不是此对象传递给switchTab函数。您可以使用idx来获取所单击的li,然后使用逻辑来添加/删除活动类。
请参见下面的代码
function switchTabs(idx) {
// this is not working
//var $li = $(this).parent(); -- you are not passing this anywhere in the function hence it is not getting
$('li').removeClass('active'); // remove all active
var $li = $('#tab' + idx).addClass('active'); // use idx to create tab id of clicked li and add active class
}
.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<ul class="nav nav-tabs">
<li role="presentation" id="tab1" class="active"><a onclick="switchTabs(1)">Tab1</a></li>
<li role="presentation" id="tab2"><a onclick="switchTabs(2)">Tab2</a></li>
</ul>