我正在做一个侧边栏,从页面的左边弹出。切换侧栏的元素是引导带导航条上的导航条品牌按钮。我在<a>标记中有一个<a>作为图标,并将这两个图标包围为一个<div>作为单击区域。看起来是这样的:
<div id = "sheath-toggle" class = "sheath-toggle-icon">
<a class="navbar-brand" href = "#"><i class = "glyphicon glyphicon-menu-hamburger"></i></a>
</div>当侧边栏没有显示时,图标就是汉堡包图标。当侧边栏弹出时,图标改变为左箭头,关闭时返回到汉堡包。
最初,这是我用来更改图标的jQuery。
$(".sheath-toggle-icon").click(function() {
if ( $(this).find("i").hasClass("glyphicon-menu-hamburger") ) {
$("i").switchClass("glyphicon-menu-hamburger", "glyphicon-menu-left");
} else if ( $(this).find("i").hasClass("glyphicon-menu-left") ) {
$("i").switchClass("glyphicon-menu-left", "glyphicon-menu-hamburger");
}
})这对我来说很好,直到我决定在页面的其他地方为另一个图标寻找另一个<i>。我发现我的脚本也在改变这个图标上的类,而它只应该在我的切换元素上切换图标。我如何重写这个脚本,使其只影响切换元素上的类,而不影响页面上的其他<i>图标?提前谢谢你的帮助。
发布于 2017-02-24 23:07:35
$("i") selects all the icons on your page.你需要像这样重写你的代码-
$(".sheath-toggle-icon").click(function() {
var icon = $(this).find("i");
if (icon.hasClass("glyphicon-menu-hamburger") ) {
icon.switchClass("glyphicon-menu-hamburger", "glyphicon-menu-left");
} else if ( icon.hasClass("glyphicon-menu-left") ) {
icon.switchClass("glyphicon-menu-left", "glyphicon-menu-hamburger");
}
})发布于 2017-02-25 00:23:33
感谢Tushar Arora的这一更正脚本
$(".sheath-toggle-icon").click(function() {
var icon = $(this).find("i");
if (icon.hasClass("glyphicon-menu-hamburger") ) {
icon.switchClass("glyphicon-menu-hamburger", "glyphicon-menu-left");
} else if ( icon.hasClass("glyphicon-menu-left") ) {
icon.switchClass("glyphicon-menu-left", "glyphicon-menu-hamburger");
}
})https://stackoverflow.com/questions/42449698
复制相似问题