javascript 带有 id AND 类的 jQuery 选择器目标元素不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19346554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery selector targeting element with id AND class does not work
提问by Fly
I have the following event-handling function:
我有以下事件处理功能:
jQuery(document).on('click', '#button .submitb', function(e){alert();});
jQuery IS included in the html document. But, if I click on a <div id="button" class="submitb">Go!</div>
nothing happens. I don't even get an error in the chrome-console.
jQuery 包含在 html 文档中。但是,如果我点击一个<div id="button" class="submitb">Go!</div>
什么都不会发生。我什至没有在 chrome 控制台中收到错误消息。
回答by Sergio
If you want to target the same element, then you cannot have a space
between selectors, that would mean .submitb
descendent of#button
.
如果您要定位的相同元素,那么你就不能有一个space
选择之间,这将意味着.submitb
的后代#button
。
And since the element has IDyou just actually need the id selector:
并且由于元素具有 ID,您实际上只需要 id 选择器:
jQuery(document).on('click', '#button', function(e){alert();});
EDIT:
编辑:
You cannot have multiple buttons with same ID!! then you should use just the class
. Or give them different ID-ending like _0
, _1
and target with [id^=button]
您不能有多个具有相同 ID 的按钮!!那么你应该只使用class
. 或者给他们不同的 ID 结尾像_0
,_1
和目标[id^=button]
回答by rorypicko
.submitb
is not a descendant of #button
to target it with jquery just use the id `#button'
.submitb
不是#button
使用 jquery 定位它的后代,只需使用 id `#button'
like this
像这样
jQuery(document).on('click', '#button', function(e){alert();});
jQuery(document).on('click', '#button', function(e){alert();});
If you want to target a div id with that class aswell you can you just move the space.
如果你想用那个类来定位一个 div id,你可以移动空间。
like this
像这样
jQuery(document).on('click', '#button.submitb', function(e){alert();});
jQuery(document).on('click', '#button.submitb', function(e){alert();});