Data-toggle and onclick doesn't work together and i'm too new to apply @epascarello 's solution to

时光总嘲笑我的痴心妄想 提交于 2020-01-14 02:41:08

问题


i have a problem a little bit like this one :

jQuery onclick doesn't work on a button with data-toggle and data-target

But i can't apply the solution from @epascarello to my problem

I'm using bootstrap and I want to add a collapse and an onclick action on the same < a>

<a class="control" data-toggle="collapse" data-target="#demo"onclick="play('audioPlayer', this)">

If I delete the data-toggle part, the onclick works, and if i delete the onclick part, the data-toggle works,

Could anyone help me ?

Thank you :)


回答1:


First give a id to your a tag

<a id="YourID" class="control" data-toggle="collapse" 
data-target="#demo"onclick="play('audioPlayer', this)">

and than your JS

$(document).on("click", "#YourID", function() {
  alert("Test");
});

Try this first

This is called delegated event handlers .You can refer to: http://api.jquery.com/on/

EXPLANATION

With delegated event handlers, you attach your event handlers to the parent element that exists at the time we run the code (it's document in this case). When the child elements are clicked (no event handlers), the event is bubbled up by browser and is handled by its parent (with event handlers attached)

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers



来源:https://stackoverflow.com/questions/35034394/data-toggle-and-onclick-doesnt-work-together-and-im-too-new-to-apply-epascare

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!