问题
I am using this code in my application:
document.getElementById("inventory_box").innerHTML = "<img src='./img/rock.gif' id='test' />";
The #inventory_box
element is present already, so it just spews out the IMG
into #inventory_box
.
What I want is to be able to click this appeared IMG
with id name test
,
but won't work like:
$("#test").click(function() {
// Run this
});
回答1:
Try this,
$(document).on('click',"#test",function() {
alert('test');
});
Read on()
回答2:
Since the image is added dynamically, you need to use event delegation to register the event handler
// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#inventory_box').on('click', '#test', function() {
// Run this
});
This will attach your event to test
image element within the #inventory_box
element,
reducing the scope of having to check the whole document
element tree and increasing efficiency.
回答3:
Consider using 'append' instead of innerHTML. Using a mix of vanilla JavaScript & jQuery seems to be causing some delay in updating the DOM with the new element. The code below works for me.
$("#inventory_box").append("<img src='./img/rock.gif' id='test' />")
$('#test').click(function(d){console.log("clicked!");});
回答4:
Your assignment of event handler runs before there is an element having such id, so after you create an element, it will not have any event handler assigned to it.
As it was suggested, easiest way to solve this common javascript error, you can assign event to a container DOM element and use jquery's event delegation to fire events on event newly added DOM elements.
But I rather not use this approach, the reason I can not give you, say, I just simply prefer not to.
Always assign events after element is created. for example:
document.getElementById("inventory_box").innerHTML = "<img src='./img/rock.gif' id='test' />";
immediately after this, execute this:
$("#test").click(function() {
// Run this
});
回答5:
$('#inventory_box img').click(function() {
// Run this
});
来源:https://stackoverflow.com/questions/19224085/jquery-functions-not-working-after-js-innerhtml-property