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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:16:26  来源:igfitidea点击:

jQuery selector targeting element with id AND class does not work

javascriptjqueryhtmleventscallback

提问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 spacebetween selectors, that would mean .submitbdescendent 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, _1and target with [id^=button]

您不能有多个具有相同 ID 的按钮!!那么你应该只使用class. 或者给他们不同的 ID 结尾像_0,_1和目标[id^=button]

回答by rorypicko

.submitbis not a descendant of #buttonto 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();});