The solution to the onclick failure problem after calling innerHTML _javascript tips

Source: Internet
Author: User

Recently wrote a project, used to innerHTML, but, found that after calling innerHTML, the onclick invalid, which is also expected, because innerHTML is inserted as a text button, so the onclick event is not recognized, We have to find another way out, we can not directly implement, but can be implemented indirectly, here is an example:

Example one: This example is not achievable by the onclick

Copy Code code as follows:

<script defer>
function Inscell (TH)

var name=th.name;
var id=th.id;
if (name== "no") {
Id.innerhtml= "<input type= ' button ' onclick= ' Inscall (this) ' value= ' online '
Name= ' no ' id= ' 1 ' > ';


}else{
Id.innerhtml= "<input type= ' button ' onclick= ' Inscall (this) ' value= ' offline '
Name= ' yes ' id= ' 1 ' > ';





}
</script>
<body>


<br/>
<span id= "MSG" >
<input type= "button" onclick= "Inscall (This)" value= "Offline" name= "yes" id= "1" >
</span>
</body>

The above example is, according to the button's name to determine whether the line, or offline ~ ~ ~ We found that when the first click, then click on the invalid ~~~~~~

At this time we can implement in disguise, as follows:
Copy Code code as follows:

<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= ' off-line ' >";
Span.name= "yes";
}else{
Span.innerhtml= "<input type=" button ' value= ' online ' > ';
Span.name= "No";
}
}
</script>
<body>


<br/>
<span id= "1" onclick= "Inscell (This)" Name= "No" >
<input type= "button" value= "Online" >
</span>
</body>

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.