DIV层和jquery点击函数
DIV layers and the jquery click function
我有一个明信片功能,它基本上是为覆盖div设置动画,然后在上面放一张明信片
<div id="overlay">
<div class="postcard">
<p>This is a postcard</p>
<a href="#">close</a>
</div>
</div>
我的jquery看起来是这样的:
$('#overlay, .postcard a').click(function(){ doSomething() })
我希望我的事件处理程序只拾取覆盖div和明信片锚点上的点击。
目前,点击所有元素,包括明信片分区。
如有任何帮助,我们将不胜感激。
这是由于Javascript的事件传播机制,您可以在以下位置阅读更多信息:
http://www.quirksmode.org/js/events_order.html
Javascript:多个mouseout事件触发
您可以通过禁用内部div的点击事件来避免这种情况,如下所示:
$('.postcard').click( function(evt) { evt.stopPropagation(); } );
如果向覆盖中添加一个单击处理程序,那么它内部的所有内容都将在单击时触发该处理程序。
要只使链接可点击,您可以使用这样的选择器(#overlay
后没有逗号):
$('#overlay .postcard a').click(function(){ doSomething() })
或者给链接本身一个id:
<div id="overlay">
<div class="postcard">
<p>This is a postcard</p>
<a id="clickMe" href="#">close</a>
</div>
</div>
$('#clickMe').click(function(){ doSomething() })
您必须打破冒泡。
举一个例子:
$('#overlay, .postcard a').click(function () {
// call other method
return false;
});
$('#overlay, .postcard a').click(function (e) {
e.preventDefault();
// call other method
});
$('#overlay, .postcard a').click(function (e) {
e.stopPropagation();
// call other method
});
如果单击某个元素或其子元素,将触发单击事件。
你可以使用事件的目标,它给出了点击的精确元素:
var selector = '#overlay, .postcard a';
$(selector).click(function(e){
var target = $(e.target);
if ( target.is(selector) ) doSomething()
})
EDIT²:这个新版本不应该触发两次:(http://jsfiddle.net/xnu8M/)
$('.postcard a').click(function(e){
var target = $(e.target);
if ( target.is('.postcard a') ) alert('a');
});
$('#overlay').click(function(e){
var target = $(e.target);
if ( target.is('#overlay') ) alert('a');
});
相关文章:
- 执行ajax成功函数-jQUERY
- 函数jquery.html()不提供数据属性集值
- 将变量放入ajax函数JQuery
- 函数jquery的未定义返回
- 如何在嵌套函数jquery上保持变量的值不变
- 用我的函数jquery给出数据/参数
- Firefox在调用函数(jquery)时冻结
- 在传递节时触发一个函数 - jquery
- 循环执行数组函数jQuery
- 在函数中调用另一个函数JQuery
- 对象不是函数-Jquery/JavaScript
- TypeError:对象不是函数-jquery
- 获取函数jQuery设置的属性
- 从函数jquery获取更新的变量值
- 切换而不是悬停函数jQuery
- 函数jQuery.animation()运行了两次行,但不起作用
- 使用函数 jQuery 获取变量
- 自执行函数 jquery 与 JavaScript 的区别
- 从回调函数 -JQuery 获取返回值
- 一个接一个地执行函数 JQUERY