开发者

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

开发者 https://www.devze.com 2023-03-28 11:44 出处:网络
Here is the thing Suppose I have an html with the following structure: <div id=\"click\"> add</div>

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 ti开发者_StackOverflow中文版me, 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


You could probably solve this problem using .live()

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


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

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


http://api.jquery.com/live

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


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');})

0

精彩评论

暂无评论...
验证码 换一张
取 消