jQuery:触发 img 上的点击不起作用
我正在 Chrome 中进行测试。
我在屏幕上有一堆“添加项目”图标,用户可以单击这些图标以将该项目添加到数据库中。我在该列表的底部还有一个按钮,它应该添加整个项目列表。
在我看来,最简单的方法是触发所有这些图标的“点击”事件(我通过图标执行此操作的原因是项目特定的值存储为 div 的属性,其中图标驻留)。
但是,我无法让它工作:各个图标的事件处理程序工作完美,并且“添加全部”按钮的事件处理程序确实会给我一个警报,如果我将其放入。但是如果我添加触发器(“点击”)命令,我没有得到任何牛肉。
我尝试通过向选择器添加“:first
”来触发仅第一个图标的点击,但这没有帮助。
$(function(){
$('#addAllItemsButton').click(function() {
alert("Caught your button click");
$('.addItemIcon').trigger('hover');
});
我读到一些文章建议浏览器不允许您触发点击事件,因此我向图标添加了一个“hover
”事件侦听器,以查看问题是否出在我想要的事件类型中扳机。答案:不,同一个故事;警报会起作用,但触发器不会。
我已将图标事件侦听器放在按钮事件侦听器之前的代码中。
这是怎么回事?感谢您的任何提示。
I'm testing in Chrome.
I have a bunch of 'add item' icons on screen that the user can click in order to add that one item to the database. I also have a button at the botton of that list, which should add the whole list of items.
It seems to me that the easiest way to do this is to trigger the 'click' event for all these icons (the reason I'm doing it via the icons is that items-specific values are stored as attributes of the div in which the icon resides).
However, I can't get it to work: the event handlers for the individual icons work perfectly, and the event handler for the add-them-all button does give me an alert if I put that in. But if I add the trigger ('click') command, I don't get no beef.
I tried triggering the click for just the first of the icons by adding ':first
' to the selector, but that didn't help.
$(function(){
$('#addAllItemsButton').click(function() {
alert("Caught your button click");
$('.addItemIcon').trigger('hover');
});
I read some posts that suggest browsers don't allow you to trigger click events, so I added a 'hover
' event listener to the icons to see if the problem is in the type of event I want to trigger. Answer: no, same story; the alert will work, but the trigger won't.
I have placed the icon event listener in the code before the button event listener.
What's going on? Thanks for any hints.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,请确保选择器有效,例如:
它应该至少为您提供
1
顺便说一句 - 我在
hover
方面遇到了一些问题。你可能会选择mouseenter
/mouseleave
first of all, be sure that the selector is valid, eg:
it should give you at least
1
btw - i experienced some issues with
hover
. you might go formouseenter
/mouseleave