cambiar la imagen en jQuery?
-
28-09-2019 - |
Pregunta
tengo este código jquery que funciona muy bien, pero la imagen al final no está cambiando a la src he especificado aquí:
jQuery:
$(document).ready( function() {
$("a.vote_up").click(function(){
//get the id
var the_id = $(this).attr('id');
//the main ajax request
$.ajax( {
type: "POST",
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function( msg ) {
$("span.vote_count#"+the_id).html(msg).fadeIn();
// my problem is here
$(".vote_up#" + the_id + " img").attr("src", "img/upvoteActive.png");
}
} );
} );
} );
el código html:
<a href='#' class='vote_up' id="$id"><img src="img/uparrow.png" /></a>
Solución
No utilice la clase en combinación con la identificación; es redundante porque ID siempre debe ser único ...
$("#" + the_id + " img").attr("src", "img/upvoteActive.png");
Además, no se puede utilizar el carácter $ en el atributo ID. Para citar el W3C sobre el atributo ID ...
ID y NAME fichas deben comenzar con una letra ([A-Za-z]) y puede ser seguido por cualquier número de letras, dígitos ([0-9]), guiones ( "-"), guiones bajos ( "_"), Dos puntos ( ":"), y los períodos ( "").
Otros consejos
Parece que está utilizando el mismo ID en múltiples ocasiones (IMG) y el recuento. Trate de hacer el identificador más exclusivo como:
<a href='#' class='vote_up' id="$id_link"><img src="img/uparrow.png" /></a>
<span class="vote_count" id="$id_count"></span>