热衷于通过鼠标获取 DOM 或 jQuery 元素?
如何通过鼠标点击获取DOM或jQuery元素? 例如,我有下一个代码:
$("*").mouseup(
function()
{
var clickedElement = ???????????????
}
);
那么,如何初始化“clickedElement”变量? 谢谢。
How to get DOM or jQuery element by mouse click?
For example I have the next code:
$("*").mouseup(
function()
{
var clickedElement = ???????????????
}
);
So, how to init 'clickedElement' variable?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在事件处理程序中,
this
指的是引发事件的 DOM 元素。要获取 jQuery 元素,只需将
this
传递给jQuery
即可。但是:使用事件委托会好得多,而不是将事件处理程序绑定到每个元素。您可以通过
event.target
:进一步说明:这不一定会为您提供单击的元素,而是为您提供释放鼠标按钮的元素,该元素可能与按钮所在的元素不同按下。您可能想要绑定到
click
事件。我还建议阅读涵盖这些基础知识的 jQuery 教程。
Inside an event handler,
this
refers to the DOM element the event was raised on.To get a jQuery element, just pass
this
tojQuery
.But: It would be much much much better to use event delegation, instead of binding an event handler to every element. You can get the origin of the event with
event.target
:And a further note: This will not necessarily give you the clicked element, but the element over which the mouse button was released, which can be different from the element the button was pressed. You might want to bind to the
click
event.I also suggest to read a jQuery tutorial where these basics are covered.
如果您不想将事件附加到每个 DOM 元素(我不推荐)...
jsFiddle 。
在这里,任何元素的事件都会一直冒泡到
document
,在那里它将被处理,并且启动事件的原始元素将位于event.target
中。If you don't want to attach an event to every DOM element (which I wouldn't recommend)...
jsFiddle.
Here, any element's event will bubble up all the way to
document
, where it will be handled, and the originating element that started the event will be inevent.target
.使用这个。 IE:
Use this. i.e.: