Ahmet
Ahmet

Reputation: 314

How can I run element's click event handler?

HTML

<div id="menu-left-left">
    <ul>
    </ul>
</div>

jQuery

var temp = "";

for (var i = 0; i < 2; i += 2) {
    temp += "<li> <a href='#' class='test'> + "Test" + </a> </li>";
}

$("#menu-left-left ul").html(temp);

$(".test").click(function() {   
    alert("Element test class");
});

I want to load #menu-left-left element using jQuery. When this code block works the menu seems to look like I want. But .test element's click event handler doesn't work. How can I run this event handler?

Upvotes: 0

Views: 62

Answers (2)

RobH
RobH

Reputation: 3612

You don't need to delegate the events as you are selecting the element after adding it in. Your problem is that the body of your loop isn't valid.

var temp = "";

for (var i = 0; i < 2; i += 2) {
    temp += "<li> <a href='#' class='test'> + "Test" + </a> </li>";
}

There is a syntax error in your string concatenation. You probably meant either:

 "<li> <a href='#' class='test'>" + Test + "</a> </li>" // Test is a variable

or

 "<li> <a href='#' class='test'>Test</a> </li>"

Here's a working version of your code:

var temp = "";

for(var i=0; i<2; i+=2) {
     temp += "<li> <a href='#' class='test'> Test </a> </li>";
}

$("#menu-left-left ul").html(temp);

$(".test").click(function() {   
    alert("Element test class");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="menu-left-left">
 <ul>

 </ul>
</div>

Upvotes: 2

Laurent S.
Laurent S.

Reputation: 6946

You should use delegated events as the element you're targetting is added dynamically. Try this :

$("#menu-left-left ul").on("click","li a.test",function() {   
alert("Element test class");

});

Upvotes: 0

Related Questions