Add event processing for dynamically generated HTML elements

Source: Internet
Author: User

Adding onclick property to dynamicly genertated HTML Element

Function klik (){
Alert ("PPP ");
}

Function addnewimg (newimageid ){
Newimg = document.Createelement('Img ');
Newimg. ID = "image" + newimageid;
Newimg = Document. getelementbyid ("divimage1"). appendchild (newimg );
Newimg.Onclick= Klik
}

It works. The new image is created and after clicking on it "PPP" is alerted.

But when I use this:

Function klik (FF ){
Alert (ff );
}

Function addnewimg (newimageid ){
Newimg = document.Createelement('Img ');
Newimg. ID = "image" + newimageid;
Newimg = Document. getelementbyid ("divimage1"). appendchild (newimg );
Newimg.Onclick= Klik ("PPP ");
}

"PPP" is alerted in the moment of executing the statement newimg.Onclick= Klik ("PPP"); and when clicking on the generated image nothing happens, even JavaScript console of Firefox stays blind.

Function addnewimg (newimageid ){
Newimg = document.Createelement('Img ');
Newimg. ID = "image" + newimageid;
Newimg = Document. getelementbyid ("divimage1"). appendchild (newimg );
VaR onc = 'ppedit ("image' + newimageid + '", "image ")';
Document. getelementbyid ("image" + newimageid ).Onclick= New function (ONC );
}

It works

Maybe an object detection be great to add too
Why?
So browsers that understand document. getelementbyid,
Document.CreateelementExecute the code.


Function addnewimg (newimageid ){
// Object detection check
If (! Document. getelementbyid &&! Document.Createelement) {Return ;}
Newimg = document.Createelement('Img ');
Newimg. ID = "image" + newimageid;
Newimg = Document. getelementbyid ("divimage1"). appendchild (newimg );
VaR onc = 'ppedit ("image' + newimageid + '", "image ")';
Document. getelementbyid ("image" + newimageid ).Onclick= New function (ONC );
}

Alternative solution:
If (! Document. getelementbyid) {return ;}
Document. getelementbyid ("image" + newimageid ).Onclick= Function (){
Ppedit (this. ID, "image ");
}

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.