简体   繁体   English

区分jquery中的“ on”点击事件

[英]Differentiating “on” click events in jquery

I have a page which has an event as follows: 我有一个页面,其中包含以下事件:

$(document).on("click","#div",function(e){

//do the operation

});

This event gets executed on both page load as well as div click. 该事件在页面加载以及div点击时都执行。 I need to differentiate between these two calls inside the event, because I have to write a condition extra only on div click and not on load . 我需要区分事件内部的这两个调用,因为我必须只在div click而不是load上写一个额外的条件。

How do I know if its from page load or div click? 我怎么知道它是来自页面加载还是来自div点击?

Edit 编辑

On load: 负载:

$(default).find('a').trigger("click") ; $(default).find('a')。trigger(“ click”); makes it trigger on load 使它在加载时触发

 $(document).on("click", "#div", function(e) { if (e.originalEvent !== undefined) {//use the originalEvent alert('human'); } else { alert('load click') } }); $('#div').click(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='div'>click</div> 

 //You can check for originalEvent element present in event object. $(document).ready(function() { $(document).on("click","#div",function(e){ if(e.originalEvent) { alert('clicked manually'); } else { alert('page load'); } }); $('#div').click(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="div"> div </div> </body> 

You could set a boolean variable in each of these like: 您可以在每个类似的变量中设置一个布尔变量:

var fromPageLoad = false;
var fromDivClick = false;

$(window).load(function() {
    fromPageLoad = true;
    //do the operation
});

$(document).on("click","#div",function(e){
    fromDivClick = true;
    //do the operation
});

and then check which condition is true with an if or a switch statement. 然后使用if或switch语句检查哪个条件为真。

[EDIT] Unless you want alerts popping out of the blue like the other answers suggest settings variables as so is the way to go. [编辑]除非您希望像其他答案一样使警报突然弹出,否则建议设置变量。

if u need to perform any action on page load you have to specify as below 如果您需要对页面加载执行任何操作,则必须指定如下

$(document).load(function(){
  alert("event on page load");
});

if the div click event then as below 如果div点击事件,则如下所示

$(#div).onclick(function(){ alert ("on div click"); })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM