当前位置: 动力学知识库 > 问答 > 编程问答 >

Adding and removing classes on forms using jQuery

问题描述:

I have two areas, one area is for enabled items, the other is for disabled items. The user can click on Add to send the content to the enabled area.

The problem is, when I change the class of the form to make it delete instead of add, nothing happens.

I've made a jsfiddle of the issue. You're suppose to be able to switch back and forth how many times you wish, not just once.

You can see in the source that the class names are actually changing but it seems that my jQuery function doesn't recognize the change.

Please see the jsfiddle-example below:

http://jsfiddle.net/crW9m/7/

Here's my HTML markup:

<div class="added">

<form class="add">

<h3>One item </h3>

<input type="submit" value="Add" />

</form>

</div>

<div class="deleted">

<form class="delete">

<h3>Second item </h3>

<input type="submit" value="Delete" />

</form>

</div>

<div id="destination">

<p>Destination for added items</p>

</div>

<div id="destination2">

<p>Destination for deleted items</p>

</div>

and here's the jQuery code that goes with it:

 $(document).ready(function() {

$(".add").click(function(event){

var $form = $(this),

$inputs = $form.find("input, select, button, textarea"),

serializedData = $form.serialize();

$form.removeClass("add").addClass("delete");

$inputs.val('Delete');

$form.appendTo("#destination");

// prevent default posting of form

event.preventDefault();

});

$(".delete").click(function(event){

var $form = $(this),

$inputs = $form.find("input, select, button, textarea"),

serializedData = $form.serialize();

//var submit = $form.find(":submit").hide();

$form.removeClass("delete").addClass("add");

$inputs.val('Add');

$form.appendTo("#destination2");

// prevent default posting of form

event.preventDefault();

});

});

网友答案:

I've created an updated version of your script.

http://jsfiddle.net/crW9m/9/

My only change was to use delegate (jQuery function on) instead of your click event. The click event is added to the actual elements matching the selector when the script is run (on page load usually). If other elements are added later they will not be affected by the event since the event was added to specific elements and not to the general selector. A delegate solves this by checking for matching elements on the actual event.

// $(".delete").click(function(event){ /*...*/ }); // Replace this with:
$(document).on('click', '.delete', function(event){ /*...*/ });

// $(".add").click(function(event){ /*...*/ }); // And replace this with:
$(document).on('click', '.add', function(event){ /*...*/ });
网友答案:

The problem is that binding to click events is made at document load, and just changing element class won't affect this bindings. Use jQuery live() method, instead of bindings.

$(".add").live("click", function(event){

instead of

$(".add").click(function(event){

Here is the jsfiddle: http://jsfiddle.net/crW9m/8/

分享给朋友:
您可能感兴趣的文章:
随机阅读: