2015-05-22 8 views
16

Ho un elenco di voci generate da PHP, ciascuna nel proprio div e ciascuna con un ID univoco. Sto cercando di sviluppare una chiamata AJAX in grado di rimuovere ogni voce in base alla loro identità, però ogni volta che faccio funzionare lo scritto di seguito, restituisce sempre 0.jQuery utilizzando più pulsanti della stessa classe per restituire un valore

<div> 
    Some entry here 
    <button id="0" class="remove">Remove</button> 
</div> 
<div> 
    Another entry here 
    <button id="1" class="remove">Remove</button> 
</div> 
// ... and so on 

<script> 
    $(".remove").click(function() { 
     var id = $(".remove").attr('id'); 
     alert(id); // debug 
     // AJAX call here 
    }); 
</script> 

precedenza ho provato la stessa cosa, tranne il contrario - l'ID restituito da PHP era nell'attributo class e l'attributo id aveva il valore 'remove' e questo solo restituiva 0 per il primo pulsante. Il secondo pulsante non ha richiamato affatto lo script jQuery.

Come posso passare un ID univoco alla stessa chiamata jQuery?

risposta

11

Prova questa

$(".remove").click(function() { 
    var id = $(this).attr('id'); // $(this) refers to button that was clicked 
    alert(id); 
}); 
6

Basta usare this.id per ottenere id dell'elemento

$(".remove").click(function() { 
 
    alert(this.id); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div> 
 
    Some entry here 
 
    <button id="0" class="remove">Remove</button> 
 
</div> 
 
<div> 
 
    Another entry here 
 
    <button id="1" class="remove">Remove</button> 
 
</div>

1
$(".remove").on("click",function() { 
    var id = $(this).attr('id'); 
    console.log(id); 
}); 
3

è necessario utilizzare la parola chiave this per fare riferimento all'elemento cliccato:

$('.remove').click(function() { 
    var id = this.id; 
    // OR 
    var id = $(this).attr('id'); 
}); 
5

L'opzione di vaniglia per i futuri spettatori.

  1. Selezionare tutti gli elementi con class remove
  2. Itera attraverso gli elementi, l'assegnazione di un gestore di clic
  3. Al clic rimuovere l'elemento genitore
  4. Accedere l'id alla console

(function() { 
 
    "use strict"; 
 
    var buttons = document.getElementsByClassName('remove'); 
 
    for (var i in Object.keys(buttons)) { 
 
     buttons[i].onclick = function() { 
 
      this.parentElement.remove(); 
 
      console.log(this.id); 
 
     }; 
 
    } 
 
})();
<div>Some entry here 
 
    <button id="0" class="remove">Remove</button> 
 
</div> 
 
<div>Another entry here 
 
    <button id="1" class="remove">Remove</button> 
 
</div>

Problemi correlati