Question

I have this code:

$(".div").click(function ()
{
    alert("hi");
});

...but when I create new div:

$("body").append("<div>1</div>");

...and click on this div, it doesn't say "hi".

I know that I can do onclick="callfunction()" on the div element, but I would like to avoid using that method.

Était-ce utile?

La solution

Problems

You were attempting to create a bind on an element that didn't yet exist - so it couldn't be bound.

You used .div as a selector. The selector .div is looking for an element with class="div" rather than an element of type div.


Solution 1 - Delegation
With delegation you create a bind on an element that exists in the structure above where you will be dynamically adding an element that you want to listen for.

To use delegation, change to this:

$("body").on("click", "div", function ()
{
    alert("hi");
});

Here is an example showing delegation vs binding on a future element without delegation:
Fiddle


Solution 2 - Bind to element on creation
The alternative would be to add the bind on the creation of the new element, that would look something like this:

$newEle = $("<div>1</div>").click( function() {
    alert("hi");
});
$("body").append($newEle);

Fiddle

Autres conseils

Use the appendChild() method to add the DIV to the end of your document. See: http://www.w3schools.com/jsref/met_node_appendchild.asp

Your other logic can follow the creation of the div.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top