Was trying to make a minesweeper in javascript and ran into this problem…
I created a table and each td is a “box” with either a mine or nothing(Currently) in it.
After I click on a box, the javascript should change the onclick from “clicked(this.id)” to an alert that says “NOPE”(made an alert just to test if something was happening), but what happends is:
- I click on “box 1”, it reveals what’s there (bomb or nothing)
- I click on it again, this time I get an alert “NOPE” – which means the onclick has changed. Good!
- I click on “box 2”, it reveals what’s there (bomb or nothing)
- I click on it again, this time I get an alert “NOPE” – which means this onclick has changed too!
- I click on “box 1” again. The clicked(this.id) runs again. (This is shown because I added a counter for each time the function runs)
For some reason, the onclick returns to its original value (clicked(this.id))..
I made a test page, a table with 2 td’s and the same thought in mind(change onclick value after it’s clicked) and it works.. I have no idea how to fix this…
The test.html that does work:
http://pastebin.com/62ayRJps
The HTML from the site that doesn’t work as intended:
http://pastebin.com/SZ6NU8j9
And the Javascript from the site that doesn’t work as intended:
http://pastebin.com/bevJHNLc
Your click event handlers are being reset because of this line in
clicked(id):Each table cell has a
onclick='clicked(this.id);'attribute in its HTML. When you assign your test functiontstto the table cell DOM object, you’re setting theonclickproperty of the DOM object, but that doesn’t change theonclickattribute of the HTML. (Yes, it’s confusing.)In the line of code above, the browser reads the
innerHTMLfrom the minesweeperdiv(which has the originalonclickattributes), concatenates it with another string, then reassigns the result back to the minesweeperdiv. This wipes out the original contents of thedivand replaces it with the new HTML (a table where every cell has the originalonclickattribute).If you want to have a message area, I suggest setting
innerHTMLon another element: DemoIn the demo, I changed line 49 (adding a
span):and line 107 (assigning the text to the
span):