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

169
Views
¿Cómo cambiar el valor de la variable del atributo html href con jQuery?

Estoy tratando de cambiar el valor de la variable del atributo html href? Post = 55 a? Post = 44 con un clic de botón sin cambiar otra variable de URL (thread = 7) usando jQuery, pero no sé cómo.

HTML

 <button class="button">button</button> <a href="posts.php?thread=7&post=55" class="post-link">Post</a>

JAVASCRIPT

 $('.button').on('click', function() { $("a").attr('href','posts.php?post=44') // this does not work because it removes ?thread=7 $("a").attr('href','posts.php?thread=7&post=44') // this also does not work because ?thread=7 is just a placeholder. I don't know what actual thread number is going to be. });

Esto es lo que tengo

 <a href="posts.php?thread=7&post=55" class="post-link">Post</a>

Esto es lo que quiero al hacer clic en el botón

 <a href="posts.php?thread=7&post=44" class="post-link">Post</a>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Para hacer lo que necesita, puede proporcionar una función a prop() (nota: no attr() *) que acepta el valor del atributo actual como argumento. Desde allí, puede usar una expresión regular para encontrar el número dentro del href actual y reemplazarlo.

El beneficio de usar este método es que funcionará sin importar en qué parte de la URL aparezca el argumento de la post .

También en el siguiente ejemplo almacené el valor de la página para configurarlo como un atributo de data en el button , pero esto puede modificarse para adaptarse a su caso de uso específico.

 $('.button').on('click', function() { $('a').prop('href', (i, href) => href.replace(/(post=)\d{1,2}/, '$1' + $(this).data('page'))); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <button class="button" data-page="44">Update post to '44'</button> <a href="posts.php?thread=7&post=55" class="post-link">Post</a>

* Consulte esta respuesta para saber por qué debería usar prop() sobre attr() .

about 4 years ago · Juan Pablo Isaza Report

0

$('.button').on('click', function() { // Get the href Value: const link = $("a").attr('href'); // posts.php?thread=7&post=44 // Split the href value by '&' (returns Array): const parts = link.split('&'); // ['posts.php?thread=7','post=44'] // Get the actual post value (may not needed?) const post = parts.slice(-1)[0]; // post=44 // remove the 'post=44' part: parts.pop() // ['posts.php?thread=7'] // Important if more than one "&" in URL: const linkBase = parts.join('&'); // Build the new URL including YOUR Post number: const newUrl = linkBase + '&post=n'; $("a").attr('href', newUrl) // Sources: // https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/split });

Tenga en cuenta que este es un ejemplo que se puede mejorar, pero está escrito con todos los pasos necesarios para un mejor seguimiento.

Espero eso ayude

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!