使用Javascript在.......上生成click事件 [英] generating a click event on ....... using Javascript

查看:69
本文介绍了使用Javascript在.......上生成click事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div网格,它代表一张地图.我希望能够在用鼠标单击时在任何div上生成click事件.我使用了以下代码片段,但均未成功完成 我得到了真实的返回值:

I have a grid of divs which represents a map. I want to be able to generate click event on any of the div as I click with my mouse. I have used following code snippet with no success though I get a true return value:

var fireOnThis = document.getElementById('someID');
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'click', true, true );
fireOnThis.dispatchEvent(evObj);

我知道不会产生任何点击,因为当我用实际的鼠标单击时,div会突出显示.

I know no click is being generated because when I click with actual mouse the div gets highlighted.

还有一个附带的问题:是否有可能区分实际的鼠标生成的点击和通过javascript本身生成的点击并阻止后面的点击?(我知道这听起来在逻辑上是错误的,但我对JS的了解并不多,所以... )

Just a side question: Is it possible that one could distinguished between actual mouse generated clicks and ones generated via javascript itself and block the later ones ?(I know it sounds logically wrong but I dont know much JS so maybe.... )

某些背景:我是在一个在线游戏网站上执行此操作的,我想通过编写chrome扩展名来自动执行日常任务.这部分是针对内容脚本的.

Some background: I am doing this for an online gaming website where I want to automate the routine tasks by writing an extension for chrome....this part is for content script.

也许我是用错误的方式看问题的……..也许实际上,div没有监听click事件,实际上是div没有被选中的原因即使事件被触发.....
New Question:给定事件(即单击特定的div),我能否确定哪个听众/元素收到了该事件?

Perhaps I am looking at problem the wrong way..... perhaps in actual, the div is not listening for the click event, the reason div doesn't get selected in actual even when the event gets fired.....
New Question: given the event (i.e., click on a particular div) can I tell which listener/element received that event ?

推荐答案

我对

My answer to this SO question presented this function, which may be useful:

function eventFire(el, etype){
    if (el.fireEvent) {
      el.fireEvent('on' + etype);
    } else {
      var evObj = document.createEvent('Events');
      evObj.initEvent(etype, true, false);
      el.dispatchEvent(evObj);
    }
}

这是关于这个问题的另一个SO问题

这篇关于使用Javascript在.......上生成click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆