简体   繁体   中英

How to Replace a Div with another Div but only once

I am trying to replace a div with another div onclick using the code below. It works fine for one instance. However, the problem is when the class appear more than once which is the case for me (multiple instances)it obviously changes all instance as they have the same class name. Is there a way to make it only change the clicked instance? Thanks

HTML

<div id="test"></div>

JavaScript (dynamically creating HTML)

var html =
 '<form action="test.php" method="get" class="myForm">' +
   '<input type="hidden" name="mID" value="' + this.id + '"/>' +
   '<input type="image" class="send" src="this.image" name ="send" alt="submit"/>' +
 '</form>';

$('div#test').append(html);


$("#test").on('click', '.send', function(e) {
e.preventDefault();

   var $form = $(this).closest('form');

   $.get($form.attr("action"), 
   $form.find(":input").serializeArray(), 
      function(data) {

  $('.myForm').replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');

});
});

 $("#test").on('submit', '.myForm', function(e) {
  return false;
});

SOLUTION;

Instead of;

  $('.myForm').replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');

CORRECT WAY;

  $form.replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');

You're already most of the way there with $form = $(this).closest('form'); but for some reason you started selected all the forms instead by using $('.myForm') , so

replace

$('.myForm').replaceWith( ...

with

$form.replaceWith( ...

First of all, you are not replacing a div, you are replacing a form (with class .myForm ). As this form is inside the div you are clicking on when you want to change your form you could use:

$(this).find(".myForm").replaceWith...
$(".targetClass").click(function(){
  var theDivBeingClicked = $(this);
  //Do something
})

Simple! I am no JQuery Expert, but we doit the traditional way!

var elements = document.getElementByID('test') we would have elemements[0] and elements[1] .... everything with the id="test" inside. but only the first element needs to be replaces.

so, our choice falls on elements[0].

$('.myForm').replaceWith(.....)

take myForm away, and add the elements array number you'd like having to be replaces, then it's always this element in the doc that is being replaces.

have fun!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM