Come trovare l'ID del pulsante su cui si fa clic?
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
}
Come trovare l'ID del pulsante su cui si fa clic?
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
}
Risposte:
È necessario inviare l'ID come parametro della funzione. Fai cosi:
<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>
Questo invierà l'ID this.idcome clicked_idè possibile utilizzare nella funzione. Guardalo in azione qui.
event.target.id(per me, sia Firefox che IE la stavano lanciando), questa è un'ottima soluzione che funziona in tutti e tre i principali browser.
In generale, le cose sono più facili da organizzare se si separano il codice e il markup. Definisci tutti i tuoi elementi, quindi nella sezione JavaScript, definisci le varie azioni che dovrebbero essere eseguite su tali elementi.
Quando viene chiamato un gestore eventi, viene chiamato nel contesto dell'elemento su cui è stato fatto clic. Quindi, l'identificatore questo farà riferimento all'elemento DOM che si è fatto clic su. È quindi possibile accedere agli attributi dell'elemento tramite quell'identificatore.
Per esempio:
<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>
<script type="text/javascript">
var reply_click = function()
{
alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
</script>
USANDO PURE JAVASCRIPT: So che è tardi ma potrebbe essere per le persone future che può aiutare:
Nella parte HTML:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
Nel controller Javascipt:
function reply_click()
{
alert(event.srcElement.id);
}
In questo modo non è necessario associare "id" all'elemento al momento di chiamare la funzione javascript.
thiscome parametro in onClick(in realtà, non usando onClick ma onChange, è forse questo il problema?). Ho anche controllato un po 'e sembra che ci sia molta confusione su questa eventvariabile che va in giro - è un parametro "implicito" o deve essere dichiarato esplicitamente come argomento (cioè function reply_click(event), che ho visto anche in alcune località)? È disponibile solo quando si assegna il listener di eventi tramite addEventListener...? Ho giocato, ma non sono riuscito a farlo funzionare.
(Penso che l' idattributo debba iniziare con una lettera. Potrebbe essere sbagliato.)
Potresti andare per la delegazione di eventi ...
<div onClick="reply_click()">
<button id="1"></button>
<button id="2"></button>
<button id="3"></button>
</div>
function reply_click(e) {
e = e || window.event;
e = e.target || e.srcElement;
if (e.nodeName === 'BUTTON') {
alert(e.id);
}
}
... ma questo richiede che tu ti senta relativamente a tuo agio con il modello di evento stravagante.
eargomento viene generato automaticamente. Se non lo è, allora abbiamo a che fare con IE6-8, che invece fornisce quell'oggetto utile tramite window.event.
in genere si consiglia di evitare JavaScript incorporato, ma raramente esiste un esempio di come farlo.
Ecco il mio modo di associare eventi ai pulsanti.
Non sono del tutto contento di quanto più a lungo il metodo raccomandato viene confrontato con un sempliceonClick attributo.
<button class="btn">Button</button>
<script>
let OnEvent = (doc) => {
return {
on: (event, className, callback) => {
doc.addEventListener('click', (event)=>{
if(!event.target.classList.contains(className)) return;
callback.call(event.target, event);
}, false);
}
}
};
OnEvent(document).on('click', 'btn', function (e) {
window.console.log(this, e);
});
</script>
<!DOCTYPE html>
<html>
<head>
<script>
(function(doc){
var hasClass = function(el,className) {
return el.classList.contains(className);
}
doc.addEventListener('click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault();
doSomething.call(e.target, e);
}
});
})(document);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script>
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var cb_addEventListener = function(obj, evt, fnc) {
// W3C model
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, false);
return true;
}
// Microsoft model
else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
}
// Browser don't support W3C or MSFT model, go on with traditional
else {
evt = 'on'+evt;
if(typeof obj[evt] === 'function'){
// Object already has a function on traditional
// Let's wrap it with our own function inside another function
fnc = (function(f1,f2){
return function(){
f1.apply(this,arguments);
f2.apply(this,arguments);
}
})(obj[evt], fnc);
}
obj[evt] = fnc;
return true;
}
return false;
};
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}
cb_addEventListener(doc, 'click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault ? e.preventDefault() : e.returnValue = false;
doSomething.call(e.target, e);
}
});
})(document);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function($){
$(document).on('click', '.click-me', function(e){
doSomething.call(this, e);
});
})(jQuery);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
Puoi eseguirlo prima che il documento sia pronto, facendo clic sui pulsanti funzionerà perché associamo l'evento al documento.
Ecco un jsfiddle
Per qualche strana ragione la insertHTMLfunzione non funziona in esso anche se funziona in tutti i miei browser.
Puoi sempre sostituirlo insertHTMLcon document.writese non ti dispiace che siano gli svantaggi
<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>
fonti:
Se non vuoi passare alcun argomento alla funzione onclick, usa semplicemente event.targetper ottenere l'elemento cliccato:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
// event.target is the element that is clicked (button in this case).
console.log(event.target.id);
}
Con javascript puro puoi fare quanto segue:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i < buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}
controllalo su JsFiddle
Puoi semplicemente farlo in questo modo:
<input type="button" id="1234" onclick="showId(this.id)" value="click me to show my id"/>
<script type="text/javascript">
function showId(obj) {
var id=obj;
alert(id);
}
id=obj;e avere soloalert(obj);
Mi dispiace è una risposta in ritardo, ma è molto veloce se lo fai: -
$(document).ready(function() {
$('button').on('click', function() {
alert (this.id);
});
});
Questo ottiene l'ID di qualsiasi pulsante cliccato.
Se vuoi semplicemente ottenere il valore del pulsante cliccato in un determinato posto, mettilo nel contenitore come
<div id = "myButtons"> buttons here </div>
e cambia il codice in: -
$(document).ready(function() {
$('.myButtons button').on('click', function() {
alert (this.id);
});
});
Spero che aiuti
Ciò registrerà l'id dell'elemento su cui è stato fatto clic: addFields.
<button id="addFields" onclick="addFields()">+</button>
<script>
function addFields(){
console.log(event.toElement.id)
}
</script>