JQuery / Dojo click handling anomaly when HTML body is updated
I am trying to install a mouse click handler on my web page programmaticly. The data handler function has a part that modifies the body like this:
document.body.innerHTML+='<div class=... id=...>X</div>'
After the addition, the click handler no long works and needs to be reconnected. How can I solve this without reconnecting the function each time (some_condition) is true?
Here is my main.js (some lines omitted for clarity):
function parsenodes(data,ioargs){
// IE does not supprt f开发者_JAVA百科orEach method
//data.forEach(function(item){
dojo.forEach(data,function(item){
//do something
if(some_condifition)
document.body.innerHTML+='<div class="some_class" id="unique_id">X</div>';
});
}
var postData = function(){
dojo.xhrPost({
//url: "/ajax/get_messages",
url: "/dbnode.json",
handleAs: "json",
load:parsenodes
});
};
function doUpdate()
{
postData();
setTimeout(doUpdate,1000);
}
function on_img_mb_down()
{
alert("mouse clicked");
}
function init()
{
console.debug("installing handler");
//$('#resim').click(function() {alert("obarey")});
handle = dojo.connect(dojo.byId("resim"),'onclick',on_img_mb_down);
console.debug(handle);
doUpdate();
}
dojo.ready(init);
//$(document).ready(init);
addendum: The anchor with id "resim" is a static HTML element:
<body>
<a id="resim" style="border:1px;" ><img id="worldpng" src="world.png" /></a>
</body>
For updated question:
When you change .innerHTML
all of the elements in there are destroyed/recreated from the updated HTML, losing the click
handlers, etc. Instead of doing that, use DOM methods to append content, instead of this:
document.body.innerHTML+='<div class="some_class" id="unique_id">X</div>';
use something like this:
dojo.query("body").append("<div class="some_class" id="unique_id">X</div>");
For previous question:
You're only rigging up the handler when the on ready
to elements that exist then, assuming you have the ID not repeated (which is a separate issue...if that's the case switch to a class), you just need to do:
dojo.connect(dojo.byId("resim"),'click',on_img_mb_down);
in your parsenodes
method, after the load of new elements completes...because when they get replaced, their click
handlers get destroyed, you need to re-create them on the new elements.
精彩评论