jQuery “$(document).on('click', 'selec

2019-07-24 15:24发布

I recently wanted to continue with an old project, but one of my javascript-functions stopped working:

jQuery(document).on('click', '#button .submitb', function(e){alert();});

jQuery IS included in the html document. But, if I click on an

<div id="button" class="submitb">Go!</div>

, nothing happens. I don't even get an error in the chrome-console. Too, I'm pretty sure that it worked some weeks ago... Anyone has an Idea what is wrong and how I can fix this?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-24 16:06

If you want to target the same element, then you cannot have a space between selectors, that would mean .submitb descendent of #button.

And since the element has ID you just actually need the id selector:

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]

查看更多
手持菜刀,她持情操
3楼-- · 2019-07-24 16:20

.submitb is not a descendant of #button to target it with jquery just use the id `#button'

like this

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.

like this

jQuery(document).on('click', '#button.submitb', function(e){alert();});

查看更多
登录 后发表回答