Dynamic Add HTML event not responding

Source: Internet
Author: User
Tags event listener

Problem description: In the page dynamic use JS added HTML set the OnClick event, the production page after the Click event is invalid and prompt:cannot read property ' xxx ' of undefined

Such as:

$ ('. Test '). Append ("<li><a href= ' javascript:void (0); ' onclick=\" Search.fn.HotSearch (' "+ V +" ') \ ">" + V + "& Lt;/a></li> ");
search.fn=function  (key) {            $ ("#_search_box"). Val (key);            Search.fn.DoSearch (true);        }, Dosearch:function(istrue) {        }} 

Problem Analysis: The main reason for this situation is that after the Dom document has been loaded,JS will not be able to listen for the element registration event because the element cannot be found, so even if the dom element is added dynamically in the future, JS is invalid. If you want to register event listening on the DOM element itself, which is dynamically added on the fly, you can take a dynamic addition to the DOM element, The element is then dynamically registered for the event listener.

In addition to the various ways to get the corresponding elements through attributes and perform event binding through the element ID, here is an alternative way:

   var html = "<li><a href= ' javascript:void (0); ' > "+ V +" </a></li> ";    var obj = $ (HTML);   Obj.bind (function  () {search.fn.HotSearch (v);});   $ ('. Test '). Append (obj);

Dynamic Add HTML event not responding

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.