Abnormal
Abnormal

Reputation: 225

jquery: insert an element and create an event on this element

Here is the thing Suppose I have an html with the following structure:

<div id="click"> add</div>
<div id="id">
<div class="item">1</div>
<div class="item">2</div>
</div>

and I have created some events on click on this "item" class via jquery.

$('.class').click(function(){ alert('1');})

The problem is, that I want to add another "item" by clicking on "click" div by stated below javascript

$('#click').click(function(){
$('#id').prepend('<div class="item">new</div>');
})

and of course I want this "item" to be clickable as well, but there is no handler on it. of course I can add it by evoking $('.class').click(.... one more time, but this is not the case because there will be 2 events on "item" 1 and "item" 2 divs.

Can anyone suggest something? Thanks in advance

Upvotes: 1

Views: 130

Answers (4)

nrip
nrip

Reputation: 131

You dont have a class called "class":

so i assume that $('.class').click(function(){ alert('1');}) is actually $('.item').click(function(){ alert('1');})

Given that, I don't quite understand your question. Do you want to do the following

When the element with class item is clicked: 1) Display the value

When the element with id click is clicked: 1) Add a new element with class item having the event handler you have already defined.

Use

$('.item').live('click', function(){ alert($(this).text()); });

$('#click').click(function(){$('#id').prepend('new');})

Upvotes: 0

cillierscharl
cillierscharl

Reputation: 7117

You could probably solve this problem using .live()

$('.item').live('click', 
    function(){ 
        alert($(this).text()); 
});

Upvotes: 2

Emyr
Emyr

Reputation: 2371

http://api.jquery.com/live

$('.class').live('click', function(){ alert('1');})

Upvotes: 0

Curtis
Curtis

Reputation: 103358

$('.class').unbind('click');
$('.class').click(.....)

This will unbind any existing event handlers for the click event on .class elements

Upvotes: 1

Related Questions