简体   繁体   中英

Why is my button duplicating when I append it?

my button should only append once for each word it finds, but somehow it appends more then once. I have no idea what could cause this to happen and therefore I posted a bit more code then just the button piece and the append piece. I think something is going wrong right before I append or so? Here you have a picture to see how it looks: 在此处输入图片说明 as you can see, 4 words... but 10 buttons or so whilst it should be 4.

function createExercise(json) {
const exercises = json.main_object.main_object.exercises;
exercises.forEach(function(exercise) {
var exer = $('<div/>', {
    'class': 'row'
  })
  .append(
    $('<div/>', {
      'class': 'col-md-3'
    })
    .append(
      $('<div/>', {
        'class': 'row'
      })
      .append($('<div>', {
        class: 'col-md-3 testforbutton',
       // text: "(button here)"
      }))
      .append($('<div>', {
        class: 'col-md-9 ExerciseWordFontSize exerciseWord',
        'id': 'eenwoordlol[' + ID123 + ']', // note the brackets will need to be escaped in later DOM queries
        text: exercise.word
      }))
    )
  ).append(
    $('<div>', {
      class: 'col-md-9',
      text: "(4 x col-3 here)"
    })
  );

$("#exerciseField").append(exer);
ID123++;
$('.testforbutton').append(getAudioForWords());
});
}

createExercise(fakejson);


function getAudioForWords() {
    var audioBtn = $('<button/>', {
    'class': 'btn btn-primary fa fa-volume-up sound'
   });
   return audioBtn;
 }

From the code, each iteration of exercises will add a button to all existing testforbutton element, duplicating buttons in previously added rows.

Just limit your selector to search of the testforbutton element in the current exer element

exer.find('.testforbutton').append(getAudioForWords());

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