Can javascript-jquery bind the same event for more than one div with the same class?
Source: Internet
Author: User
KeywordsJavascriptphpcsshtmlhtml5
Just might not be clear, I re-describe:
Start isa1
$ ('. a '). bind (' click ', function () { Call jquery to clone a label and make some other changes });
And then it turns out.
a1`a2
Question: Why click A1 to call the above jquery, and A2 not? The 1-3 floor method I have tried, or useless.
Reply content:
Just might not be clear, I re-describe:
Start isa1
$ ('. a '). bind (' click ', function () { Call jquery to clone a label and make some other changes });
And then it turns out.
a1`a2
Question: Why click A1 to call the above jquery, and A2 not? The 1-3 floor method I have tried, or useless.
$('.a').on('click',function(e){ alert(1) })
Landlord can try this, the official recommendedon
That is because the dynamic addition of elements, it is recommended that the landlord to see how to dynamically add elements how to bind the event. Probably the code is like this.
$('div').on('click','.a',function(){})
Why can't you use it? Because the elements you bind are already bound after the page document structure is generated, it is impossible to use the previous click Method with the dynamically generated DOM structure, so you need to rebind or bind dynamically.
Of course, if not, then you can consider the above event encapsulated into a method, and then//to do inside the recursive call ~
Oh, there is no natural binding when the instance is bound. There used to be a live method to solve your problem, now it seems to change to another way (name), check the manual.
Yes, you can.
If it is added dynamically, I feel like this can be $ (document). On (' click ', '. A ', function () {...}) ;
That is your cloning problem, landlord can look at the Clone () method, passed in the parameter true, the element bound by the method is cloned together. Or just use the proxy method mentioned above.
$('body').click(function(e){ var tar = e.target; if($(tar).hasClass('a')){ xxxxx }});
That's OK!
1 floor did not answer to the point, indeed is the problem of dynamic append DOM, so need to through the delegation of the parent node monitoring to solve, the simplest is the delegation of the document node, after all, all the DOM is appended to the descendants of the document node: $ (document). On (' click ', '. A ', function ( ){...})
The dynamically added Dom listens to its parent elements, such as
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.