.click() 和实际单击按钮之间的区别?(javascript/jQuery)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11127908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between .click() and actually clicking a button? (javascript/jQuery)
提问by Goose
I'm trying to figure out this weird issue I've been having, and the root cause is the difference between a live click and triggering .click()
.
我试图找出我一直遇到的这个奇怪的问题,根本原因是实时点击和触发.click()
.
I won't get into the details of the problem, but basically when you click on the input button it works fine (has an onclick
event). But if I call .click()
from somewhere else (instead of physically clicking the button) it doesn't work properly.
我不会深入研究问题的细节,但基本上当你点击输入按钮时它工作正常(有一个onclick
事件)。但是如果我.click()
从其他地方打电话(而不是物理点击按钮),它就不能正常工作。
My question is - is there a way to truly replicate an actual click on a button?
我的问题是 - 有没有办法真正复制按钮上的实际点击?
EDIT
编辑
The problem: I'm opening a new window (aspx page) that loads an inline PDF. If I actually click on the link, the window opens fine and the PDF loads. If I use .click()
the window opens and I'm prompted to download the PDF file.I've been through Adobe Reader settings, browser settings, and registry settings about the prompting - I understand that these can be factors to the big picture, but right now I'm concerned about why the behavior between a mouse click and .click() are doing anything different at all.
问题:我正在打开一个加载内联 PDF 的新窗口(aspx 页面)。如果我真的点击链接,窗口会打开,PDF 加载。如果我使用.click()
该窗口,系统会提示我下载 PDF 文件。我已经完成了有关提示的 Adobe Reader 设置、浏览器设置和注册表设置 - 我知道这些可能是影响全局的因素,但现在我担心为什么单击鼠标和 .click( ) 正在做任何不同的事情。
采纳答案by Dvir Azulay
I use this function to truly mimic a mouse click:
我使用这个函数来真正模拟鼠标点击:
function clickLink(link) {
var cancelled = false;
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0,
false, false, false, false,
0, null);
cancelled = !link.dispatchEvent(event);
}
else if (link.fireEvent) {
cancelled = !link.fireEvent("onclick");
}
}
回答by Troy Alford
Before reading the below, which discusses how to circumvent the problem, let me answer more fully why you're having the problem to begin with:
在阅读以下讨论如何规避问题的内容之前,让我更全面地回答您开始遇到问题的原因:
Modern browsers take different actions for links based on things like which mouse button you clicked with, whether you held Shift/ Ctrl/ Alt, and so on. As an example, in Chrome, if you middle-click a link instead of left-clicking, the browser will automatically open the window in a new tab.
现代浏览器根据您单击的鼠标按钮、是否按住Shift/ Ctrl/等内容对链接采取不同的操作Alt。例如,在 Chrome 中,如果您单击中间链接而不是左键单击,浏览器将自动在新选项卡中打开窗口。
When you use .click()
, jQuery has to make assumptions about the "way" in which you clicked - and you get defaulted behavior - which in your case, is not the correct behavior. You need to specify the "correct" settings to the browser in the form of MouseEvents
settings in order to fix the issue.
当您使用 时.click()
,jQuery 必须对您单击的“方式”做出假设 - 并且您会获得默认行为 - 在您的情况下,这不是正确的行为。您需要以设置的形式向浏览器指定“正确”的MouseEvents
设置才能解决问题。
Now, on to a short discussion of ways to fix it:
现在,对修复它的方法进行简短讨论:
When you are using jQuery's .click()
event with no parameters, this is not actually "faking a click" on the element in question. Instead, according to the jQuery documentation at http://api.jquery.com/click/:
当您使用.click()
不带参数的jQuery事件时,这实际上并不是对相关元素进行“假点击”。相反,根据http://api.jquery.com/click/上的 jQuery 文档:
... when
.click()
is called without arguments, it is a shortcut for .trigger("click")
...当
.click()
不带参数调用时,它是 .trigger("click") 的快捷方式
This means that when you fire $('#div1').click()
- if there is no actual jQuery handler for the 'click'
event, you will get default processing. So, consider these two cases:
这意味着当您触发时$('#div1').click()
- 如果该'click'
事件没有实际的 jQuery 处理程序,您将获得默认处理。因此,请考虑以下两种情况:
Case 1:
案例一:
<a id='myLink' href='/some/link/'>Click me!</a>
<script type='text/javascript'>
$('#myLink').click();
</script>
In this first scenario, the .click()
call does nothing, because there is no handler for it. The event triggers, but there is nothing to catch it and respond - so the a
tag's default handling is used, and the user is taken to /some/link/
- and since you haven't specified which mouse button or any other parameters - it's truly default.
在第一个场景中,.click()
调用什么都不做,因为它没有处理程序。事件触发,但没有任何东西可以捕获它并做出响应——所以使用了a
标签的默认处理,并且用户被带到/some/link/
——而且由于你没有指定哪个鼠标按钮或任何其他参数——它是真正的默认值。
Case 2:
案例2:
<a id='myLink' href='/some/link/'>Click me!</a>
<script type='text/javascript'>
$('#myLink').bind('click', function (ev) {
ev.preventDefault();
ev.stopPropagation();
alert('you clicked me!');
}).click();
</script>
In this scenario, because a click
handler was created, when the user clicks the link - the ev.preventDefault()
and ev.stopPropagation()
calls will stop the default handling from occuring, and the alert will be fired.
在这种情况下,因为click
创建了一个处理程序,当用户单击链接时 -ev.preventDefault()
和ev.stopPropagation()
调用将停止发生默认处理,并且将触发警报。
At this point, however, you have an ev
object which represents the MouseEvents
- and you could change the settings if you desired. For instance, you could do the following:
但是,此时您有一个ev
代表MouseEvents
-的对象,如果需要,您可以更改设置。例如,您可以执行以下操作:
ev.altKey = true; // Held Alt
ev.button = 1; // Middle Mouse Button
These settings will change the default method of handling the event.
这些设置将更改处理事件的默认方法。
Alternative, non-jQuery solution
替代的非 jQuery 解决方案
You can also truly simulate a button-click by adapting the following code.
您还可以通过修改以下代码来真正模拟按钮单击。
function fakeClick(event, anchorObj) {
if (anchorObj.click) {
anchorObj.click()
} else if(document.createEvent) {
if(event.target !== anchorObj) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var allowDefault = anchorObj.dispatchEvent(evt);
// you can check allowDefault for false to see if
// any handler called evt.preventDefault().
// Firefox will *not* redirect to anchorObj.href
// for you. However every other browser will.
}
}
}
(For a more full implementation, see the original post at: How can I simulate a click to an anchor tag?- and look at the selected answer)
(有关更完整的实现,请参阅原始帖子:如何模拟对锚标记的点击?- 并查看所选答案)
This will actually fake the browser into believing that you mouse-clicked the anchor / span / etc by building the event from scratch in the same way that the browser's default handlers do - except that you can override some of the settings. I don't suggest this approach, however, as it's a lot more prone to breaking on cross-browser application and you have to figure out what all of the parameters map to.
这实际上会使浏览器相信您通过以与浏览器的默认处理程序相同的方式从头构建事件的鼠标单击了锚点/跨度等 - 除了您可以覆盖某些设置。但是,我不建议使用这种方法,因为它更容易破坏跨浏览器应用程序,您必须弄清楚所有参数映射到什么。
回答by Himanshu Shekhar
$('img').click(function(event){
console.log(event.hasOwnProperty('originalEvent')); // output : true
});
$('img').trigger("click",function(event){
console.log(event.hasOwnProperty('originalEvent')); // output : false
});
回答by Sunil Kumar
To create and trigger a click event same as user-click :
要创建和触发与 user-click 相同的点击事件:
function simulateClick() {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
var cb = document.getElementById('checkbox'); //whichever element you want to click
var cancelled = !cb.dispatchEvent(event);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
}
of course, call the function like this.
当然,像这样调用函数。
simulateClick();
Source : https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
来源:https: //developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
note : initMouseEvent() is deprecated. Avoid using it, instead use MouseEvent() as shown in this solution.
注意: initMouseEvent() 已弃用。避免使用它,而是使用 MouseEvent() ,如本解决方案中所示。