[英]How do I select an element by it's toggled class in Javascript?
嘿,我有一個似乎是一個簡單的問題,但有一些麻煩。 我想只在我點擊漢堡包切換菜單的X時顯示一條警告信息。 任何幫助表示贊賞。
這是我在我的代碼中引用的代碼: https ://codepen.io/toshvelaga/pen/wLJYKL
我已經嘗試過使用下面的代碼了,但是我收到了兩次警報消息,也點擊了漢堡而不僅僅是X.
$(document).ready(function(){
$('#nav-icon3').click(function(){
$(this).toggleClass('open');
$('#nav-icon3.open').click(function() {
alert("hello");
});
});
});
檢查元素是否在(單個)處理程序中具有open
類,如果是,則記錄hello
:
$('#nav-icon3').click(function() { if (this.matches('.open')) { console.log("hello"); } $(this).toggleClass('open'); });
/* Icon 3 */ #nav-icon3 { width: 60px; height: 45px; position: relative; margin: 50px auto; -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); -webkit-transition: .5s ease-in-out; -moz-transition: .5s ease-in-out; -o-transition: .5s ease-in-out; transition: .5s ease-in-out; cursor: pointer; } #nav-icon3 span { display: block; position: absolute; height: 9px; width: 100%; background: #d3531a; border-radius: 9px; opacity: 1; left: 0; -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); -webkit-transition: .25s ease-in-out; -moz-transition: .25s ease-in-out; -o-transition: .25s ease-in-out; transition: .25s ease-in-out; } #nav-icon3 span:nth-child(1) { top: 0px; } #nav-icon3 span:nth-child(2), #nav-icon3 span:nth-child(3) { top: 18px; } #nav-icon3 span:nth-child(4) { top: 36px; } #nav-icon3.open span:nth-child(1) { top: 18px; width: 0%; left: 50%; } #nav-icon3.open span:nth-child(2) { -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); -o-transform: rotate(45deg); transform: rotate(45deg); } #nav-icon3.open span:nth-child(3) { -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); -o-transform: rotate(-45deg); transform: rotate(-45deg); } #nav-icon3.open span:nth-child(4) { top: 18px; width: 0%; left: 50%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="nav-icon3"> <span></span> <span></span> <span></span> <span></span> </div>
我們將向第三個span
元素添加一個click事件監聽器,這是X在這種情況下的位置(我假設)。
$(document).ready(function() {
$('span:nth-child(3)').click(function () {
alert('X has been clicked')
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.