Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
Haga clic en jQuery sin vincular después de la llamada Ajax que modifica la página HTML usando el método html () del elemento de página

Estoy usando jQuery v3.6.0 en una página que debería permitir dinámicamente a un usuario marcar/desmarcar un elemento que se muestra en la página.

Aquí está mi fragmento de código:

HTML

 <div id="37.3" class="social-info-container"> <div id="VK7n" class="social bookmarkable"> <i title="Bookmarks" class="fa fa-bookmark"></i>0 </div> </div>

JavaScript

 function bookmarkItem(id, elem_id){ let [ctid, oid] = id.split('.'); console.log(`Posting bookmark for item with content_type: ${ctid}, object_id: ${oid}`); $.ajax({ type: "POST", headers:{'X-CSRFToken': special_csrf_token }, url: social_bookmark_url, data: { cid: ctid, oid: oid, note: '' }, dataType: "json", success: function(resultData) { console.log(`Reponse ok: ${resultData.ok}`); console.log(`Elem id: ${elem_id}`); $(`div#${elem_id}.social.bookmarkable > i.fa.fa-bookmark`).toggleClass('bookmarked'); let orig_html = $(`div#${elem_id}`).html(); let old_count = $(`div#${elem_id}`).text(); let new_count = resultData.count; let new_html = orig_html.replace(old_count,new_count) console.log(old_count); console.log(orig_html); console.log(new_count); console.log(new_html); $(`div#${elem_id}`).html(new_html); }, error: function(xhr, status, error) { if (xhr.status == 403){ window.location.href = login_url; } else { alert(`Something went wrong: ${xhr.statusText}`); } } }); } $().ready(function(){ $('.social.bookmarkable .fa.fa-bookmark').on('click', function(e) { alert('Clicked!'); let elem_id = $(this).closest('div.social.bookmarkable').attr('id'); console.log(`Elem id (1): ${elem_id}`); let id = $(this).closest('div.social-info-container').attr('id'); bookmarkItem(id, elem_id); }); });

Cuando hago clic en el icono de marcador, funciona UNA VEZ; después de eso, tengo que actualizar la página para que vuelva a funcionar. Pensé que usar el método on() para vincular el evento de clic evitaría este problema.

¿Por qué el evento se activa solo una vez y cómo soluciono esto?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Está reemplazando el elemento al que está vinculado el controlador de eventos. El uso .on() solo funcionará si el elemento al que lo vincula todavía existe. También debe delegar el controlador a un elemento que siempre existirá y luego usar, por ejemplo, el contexto del selector para filtrar el elemento que desea.

 function bookmarkItem(id, elem_id) { let [ctid, oid] = id.split('.'); console.log(`Posting bookmark for item with content_type: ${ctid}, object_id: ${oid}`); // Fake response to the AJAX call let resultData = { ok: 'ok', count: 1 }; $(`div#${elem_id}.social.bookmarkable > i.fa.fa-bookmark`).toggleClass('bookmarked'); let orig_html = $(`div#${elem_id}`).html(); let old_count = $(`div#${elem_id}`).text(); let new_count = resultData.count; let new_html = orig_html.replace(old_count,new_count) console.log('old_count', old_count); console.log('orig_html', orig_html); console.log('new_count', new_count); console.log('new_html', new_html); $(`div#${elem_id}`).html(new_html); } $().ready(function(){ // Attach handler to an element which does not go away, and filter // to only match clicks on the element you want. // https://api.jquery.com/jquery/#selector-context $('.social.bookmarkable').on('click', '.fa.fa-bookmark', function(e) { let elem_id = $(this).closest('div.social.bookmarkable').attr('id'); let id = $(this).closest('div.social-info-container').attr('id'); console.log('Bookmark clicked: elem_id', elem_id, '; id', id); bookmarkItem(id, elem_id); }); });
 .bookmarked { background-color: black; color: white; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="37.3" class="social-info-container"> <div id="VK7n" class="social bookmarkable"> <i title="Bookmarks" class="fa fa-bookmark">Click me</i>0 </div> </div>

Ya hay muchos ejemplos de esto aquí en SO, buscando palabras clave como " jquery solo una vez ", o " jquery replace handler once " las muestra. Lo sé bien porque he hecho esa búsqueda en el pasado :-) Por ejemplo:

  • jQuery: el evento `on` no funciona después de jQuery.replaceWith
  • jquery haga clic solo disparando una vez
  • El evento de clic de JQuery funciona solo una vez
  • El evento Jquery .change () se activa solo una vez
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!