[英]Jquery selector issue
I have the following html markup on my page, 我的页面上有以下html标记,
<div id="sig_container">
<div id="layer1" class="layer ui-draggable ui-resizable ui-resizable-autohide">
<div id="layer2" class="layer ui-draggable ui-resizable ui-resizable-autohide">
<div id="layer3" class="layer ui-draggable ui-resizable selected ui-resizable-autohide">
</div>
On this page I am trying to select the #sig_container div without selecting any of the children. 在这个页面上,我试图选择#sig_container div,而不选择任何一个孩子。 However I am having an issue doing so.
但是我遇到了一个问题。 The selector either selects everything or nothing.
选择器要么选择所有内容,要么不选
Thanks in advance Daniel 在此先感谢丹尼尔
Edit: Sorry i should add I am trying to add a click event on the container. 编辑:对不起,我应该添加我试图在容器上添加一个点击事件。 So i want the event to fire only when i click the container and not the children.
所以我希望只有当我点击容器而不是孩子时才会触发事件。
You can accomplish what you want by testing the event.target
of the click event. 您可以通过测试click事件的
event.target
来完成您想要的任务。
$('#sig_container').click(function( event ) {
if( event.target === this ) {
// the children were not clicked, so run your code
}
});
The reason for this is that click events naturally bubble, so if you click one of the children, the event bubbles up to the sig_container
and fires its handler. 这样做的原因是点击事件自然会冒泡,所以如果你点击其中一个孩子,事件会冒泡到
sig_container
并触发其处理程序。
With this solution, you make sure that the target
of the event was actually the sig_container
before it fires the code. 使用此解决方案,您可以确保在触发代码之前事件的
target
实际上是sig_container
。
So basically: 所以基本上:
this
is the sig_container
this
是sig_container
event.target
is the actual element clicked event.target
是单击的实际元素
if this
is the same as the event.target
run the code 如果
this
与event.target
相同, event.target
运行代码
This selector will select only the <div id="sig_container">
: 此选择器将仅选择
<div id="sig_container">
:
$('#sig_container')
If you think it's selecting the children as well, it's not: 如果你认为它也在选择孩子,那不是:
alert($('#sig_container').length); // alerts 1
$('#sig_container')
should do the trick. 应该做的伎俩。 If it doesn't, are you passing the html through anything that mangles IDs?
如果没有,你是否通过任何破坏ID的内容传递html?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.