单击一对元素时发生的事件
Event when a pair of elements are clicked
我有5个具有类.home
和唯一id的元素,以及一个具有类.btn1
的按钮。如果在.btn1
之后单击.home
,反之亦然,则应执行一个功能。我不知道我应该使用什么jQuery方法。
试试这个:
<!DOCTYPE html>
<html>
<head>
<style>
.active {
background-color: skyblue;
}
</style>
</head>
<body>
<div class="home">I am Div1</div>
<div class="home">I am Div2</div>
<div class="home">I am Div3</div>
<div class="home">I am Div4</div>
<div class="home">I am Div5</div>
<button class="btn">Run</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var divReady = false;
var btnReady = false;
$(".btn").on("click",function(){
btnReady = true;
$(this).addClass("active");
if (divReady)
fun();
})
$("div").on("click",function(){
divReady = true;
$("div").removeClass("active");
$(this).addClass("active");
if (btnReady)
fun();
})
function fun() {
alert("I am working!")
$(".btn,div").removeClass("active");
btnReady = false;
divReady = false;
}
})
</script>
</body>
</html>
我不认为有什么特定的jQuery技巧。
为什么不使用类来存储状态?
$(function() {
$(".home").click(function () {
$(this).addClass("active");
if ($(".btn1").hasClass("active")) {
console.log("Doing something");
}
});
$(".btn1").click(function () {
$(this).addClass("active");
if ($(".home").hasClass("active")) {
console.log("Doing something");
}
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<button class = 'btn1' >Button</button>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
只需计算事件发生的次数,并存储事件。使用Array可以很容易地做到这一点:
//create an array to store events
events=[];
//create a handler function
function handler(event){
//add the event to our array
events.push(event);
if(events.length==2){
//two events fired:
//first event:
a=events[0];
//second:
b=events[1];
//do whatever
}
}
//add an eventlistener that calls our handler and passes 'documentclick'
document.addEventListener("documentclick",function(){handler("click")});
相关文章:
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 将事件聚焦/模糊在可编辑内容的元素上
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 在IE8中不起作用的元素上触发单击事件
- 正在ng重复元素上添加事件
- 单击p元素时的javascript触发事件
- 存在每个时间元素的javascript事件
- Firefox:点击并更改未附加到文档树中的复选框元素上的事件
- 有没有一种方法可以让内联事件处理程序在元素创建后立即执行
- 将jQuery事件应用于所有类元素
- 在IE8上使用jQuery克隆HTML5元素和事件
- 单击其他元素时,我如何使用 jQuery 忽略更改事件
- 访问代码生成的输入元素上的keyup事件
- 如何查明鼠标按下事件是否发生在滚动条上或元素中的其他任何位置
- 当元素到达屏幕上的某个位置时触发事件
- Mootools:如何在点击时保持元素高亮显示并停止所有事件
- 将事件侦听器添加到文档,而不是签入元素存在,然后添加事件侦听器
- JQuery:使用clone()生成的元素不采用原始的事件属性
- 从其他元素上的单击事件访问image src属性
- 触发“三个”的点击事件.元素