How to execute an insert only once via javascript/jQuery

Asked

Viewed 279 times

0

I have a situation where I need to insert a single div into a block via jQuery, is there any function already defined that ensures that this block will be inserted only once? Without me having to check with if

if (!jQuery('.product').parents('.product-info').has('.quickreview').length {
    jQuery('.product').parents('.product-info').prepend("<div class="quickreview"></div>");
}

3 answers

2

I would use a logic for this, create a bool to see if it is already created, if you go through if once it becomes false and will no longer enter it

Thus:

var needToCreate = true;

if (!jQuery('.product').parents('.product-info').has('.quickreview').length && needToCreate) {
    jQuery('.product').parents('.product-info').prepend("<div class="quickreview"></div>");
    needToCreate = false;
}
  • 1

    The missing parenthesis was the fault of the person who edited the boy’s post, in the original had correctly placed if parentese.

  • Thank you for clarifying!

1

See if with the method one help you:

$("#btn1").one("click", function(){                   // executa apenas uma vez
  $("#local1").prepend("<p>Qualquer coisa - uma vez</p>");
})

$("#btn2").on("click", function(){                   // executa varias vezes
  $("#local2").prepend("<p>Qualquer coisa - mais de uma vez</p>");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="btn1">inserir</button>  
<div id="local1"></div>
<hr>
<button id="btn2">inserir</button>  
<div id="local2"></div>

0

If you want to understand when the FOD is changed you should use Mutationobserver. This allows to define a callback that executes whenever there is a change in a given element and its descendants.

document.getElementById("inserir").addEventListener("click", function() {
  document.getElementById("conteudo").innerHTML = "<div class='product'>Produto</div>";
});

//no pai do que pretende escutar as alterações
const targetNode = document.getElementById('conteudo'); 
const config = { childList: true, subtree: true};

const observer = new MutationObserver(function(mutationsList) {
  for (let mutation of mutationsList) { //para cada uma das alterações no DOM
    if (mutation.type == 'childList') { //se afeta os filhos
      const removedIds = [...mutation.removedNodes].map(x => x.id); //apanhar os id's
      if (!removedIds.includes("teste")){ //se o id existe é porque foi inserido
        console.log("teste já inserido");
      }
    }
  }
}); 

observer.observe(targetNode, config);
<div id="conteudo">
  <div id="teste">Div teste aqui</div>
</div>
<button id="inserir">Uma única vez</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.