2012-02-03 70 views
2

当点击页面背景(#page)时,我需要触发一个事件(例如隐藏浮动购物车),但点击内部内容时不会发生此事件。所以我需要这个事件发生在空间:页面减去内容。我如何实现它?由于排除父div的选择器

如果我有这样的结构:

<body> 
<div id="page"> 
    <div id="content"> 
    here 
    </div> 
</div> 
</body> 

var outer= jQuery("#page"); 
jQuery(outer).click(function(){ 
    jQuery(cos_de_cumparare).toggle(); 
}); 

回答

2

,你可以检查事件的目标,并采取相应的行动

var outer= jQuery("#page"); 
outer.click(function(e){ 
     //trigger the event only if the target of the click is the page 
     if(e.target.id === 'page'){ 
     alert('click'); 
     } 
}); 

这里小提琴http://jsfiddle.net/wNsd7/

+0

我测试过,这似乎是最优雅的解决方案。我感谢你们所有人的帮助。问候 – Kandinski 2012-02-03 11:37:24

1

要做到这一点,你可以停止事件传播上链。

通常的方法做,这是一个click事件附加到子元素,并从停止传播有这样的:

$("#page div").click(function(e){ 
    e.stopPropagation(); 
}) 

Here's an example

+0

不,我不认为这与他正在尝试做什么有关 – 2012-02-03 10:29:38

+0

我恭敬地不同意:) – 2012-02-03 10:33:22

+0

啊好吧,你打算沉迷于其他!我一开始并没有得到它!是的这绝对有效,但可能会导致事件委派的问题。 :) – 2012-02-03 10:36:23

1

试试这个,检查http://jsfiddle.net/qgUjb/4/

$("#page").click(function(event) { 
    if(event.target.id == "content") return; 
    $("#content").toggle(); 
});