Solution to onclick failure after innerHTML is called

Source: Internet
Author: User

I recently wrote another project and used innerHTML. However, it is expected that onclick becomes invalid after innerHTML is called, because innerHTML is a button inserted in text format, therefore, The onclick event cannot be identified. We have to find another way out. We cannot implement it directly, but indirectly. The following is an example:

Example 1: onclick is not implemented in this example.
Copy codeThe Code is as follows:
<Html>
<Head>
<Script defer>
Function insCell (th)

Var name = th. name;
Var id = th. id;
If (name = "no "){
Id. innerHTML = "<input type = 'button 'onclick = 'encall( this) 'value = 'hangzhou'
Name = 'no' id = '1'> ";


} Else {
Id. innerHTML = "<input type = 'button 'onclick = 'encall( this) 'value = 'deprecation'
Name = 'yes' id = '1'> ";





}
</Script>
</Head>
<Body>


<Br/>
<Span id = "msg">
<Input type = "button" onclick = "insCall (this)" value = "deprecate" name = "yes" id = "1">
</Span>
</Body>
</Html>

In the preceding example, the button name is used to determine whether to go online or offline ~~~ We found that when you click the button for the first time, it will be invalid if you click it again ~~~~~~

At this time, we can implement it in disguise as follows:
Copy codeThe Code is as follows:
<Html>
<Head>
<Script defer>
Function insCell (th)
{
Var name = th. name;
Var id = th. id;
Alert (name + "--" + id );
Var span = document. getElementById (id );
If (name = "no "){

Span. innerHTML = "<input type = 'button 'value = 'deprecation '> ";
Span. name = "yes ";
} Else {
Span. innerHTML = "<input type = 'button 'value = 'hangzhou'> ";
Span. name = "no ";
}
}
</Script>
</Head>
<Body>


<Br/>
<Span id = "1" onclick = "insCell (this)" name = "no">
<Input type = "button" value = "online">
</Span>
</Body>
</Html>

Related Article

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.