Jump to content

What's wrong with this javascript code?


aooga

Recommended Posts

<script type="text/javascript">

function a() {

document.getElementById('2').innerHTML = "<p onclick='b()'>a</p>";

}

function b() {

document.getElementById('2').innerHTML = "hello"; // this doesn't work

document.getElementById('3').innerHTML = "hello"; // this does

}

</script>

 

<p id='1' onclick='a()'>1</p>

<p id='2' onclick='a()'>2</p>

<p id='3' onclick='a()'>3</p>

Link to comment
Share on other sites

I've made the code as small as possible to isolate the problem, but this should be enough to demonstrate it.

When I click on 1, 2 or 3 then 2 becomes a. Then when I click on a, 3 becomes hello, but b does not become hello. I'm at a loss as to why.

Btw: if function a() {

document.getElementById('2').innerHTML = "<p onclick='b()'>a</p>";

document.getElementById('2').innerHTML = "hello";

}

this would work. It's only if

document.getElementById('2').innerHTML = "hello";

is in b() that it doesn't. I'm REALLY curious about this, what am I missing?

Link to comment
Share on other sites

It does work. When you click on "a" generated by the JavaScript, you change 2 and 3 to hello, but the problem is that clicking "a" on 2 also triggers 2's a() onclick, so you change it back. It happens so fast you just don't see it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.