¿Cómo encontrar la identificación del botón en el que se hace 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()
{
}
¿Cómo encontrar la identificación del botón en el que se hace 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()
{
}
Respuestas:
Debe enviar la ID como los parámetros de la función. Hazlo asi:
<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>
Esto enviará el ID this.idcomo clicked_idel que se puede utilizar en su función. Véalo en acción aquí.
event.target.id(para mí, tanto Firefox como IE lo estaban lanzando), esta es una gran solución que funciona en los tres principales navegadores.
En general, las cosas son más fáciles de mantener organizadas si separas tu código y tu marcado. Defina todos sus elementos y luego, en su sección de JavaScript, defina las diversas acciones que deben realizarse en esos elementos.
Cuando se llama a un controlador de eventos, se llama dentro del contexto del elemento en el que se hizo clic. Entonces, el identificador esto se referirá al elemento DOM en el que hizo clic. Luego puede acceder a los atributos del elemento a través de ese identificador.
Por ejemplo:
<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>
USO DE JAVASCRIPT PURO: Sé que es tarde, pero puede ser para las futuras personas a las que puede ayudar:
En la parte HTML:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
En el controlador Javascipt:
function reply_click()
{
alert(event.srcElement.id);
}
De esta manera, no tenemos que vincular el 'id' del Elemento al momento de llamar a la función javascript.
thiscomo parámetro en onClick( en realidad, no usando onClick sino onChange, ¿ese es quizás el problema?). También he revisado un poco y parece haber mucha confusión sobre esta eventvariable: ¿es un parámetro "implícito" o tiene que expresarse explícitamente como argumento (es decir function reply_click(event), lo que también he visto en algunos lugares)? ¿Solo está disponible al asignar el detector de eventos a través de addEventListener...? He jugado un poco, pero no pude hacerlo funcionar.
(Creo que el idatributo debe comenzar con una letra. Podría estar equivocado).
Podrías ir para la delegación del evento ...
<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);
}
}
... pero eso requiere que te sientas relativamente cómodo con el loco modelo de evento.
eargumento se genera automáticamente. Si no es así, entonces debemos tratar con IE6-8, que en su lugar proporciona ese objeto útil a través de window.event.
generalmente se recomienda evitar JavaScript en línea, pero rara vez hay un ejemplo de cómo hacerlo.
Aquí está mi forma de adjuntar eventos a los botones.
No estoy completamente satisfecho con cuánto tiempo más se compara el método recomendado con un onClickatributo simple .
<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>
Puede ejecutar esto antes de que el documento esté listo, hacer clic en los botones funcionará porque adjuntamos el evento al documento.
Aquí hay un jsfiddle
Por alguna extraña razón, la insertHTMLfunción no funciona a pesar de que funciona en todos mis navegadores.
Puede reemplazar siempre insertHTMLcon document.writesi no me importa de inconvenientes
<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>
Fuentes:
Si no desea pasar ningún argumento a la función onclick, solo use event.targetpara obtener el elemento cliqueado:
<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 puedes hacer lo siguiente:
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);
};
}
compruébalo en JsFiddle
Simplemente puede hacerlo de esta manera:
<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;y simplemente teneralert(obj);
Lo siento, es una respuesta tardía, pero es muy rápido si haces esto: -
$(document).ready(function() {
$('button').on('click', function() {
alert (this.id);
});
});
Esto obtiene la identificación de cualquier botón que se haga clic.
Si solo desea obtener el valor del botón en un lugar determinado, simplemente colóquelos en un contenedor como
<div id = "myButtons"> buttons here </div>
y cambie el código a: -
$(document).ready(function() {
$('.myButtons button').on('click', function() {
alert (this.id);
});
});
espero que esto ayude
Esto registrará la identificación del elemento en el que se ha hecho clic: addFields.
<button id="addFields" onclick="addFields()">+</button>
<script>
function addFields(){
console.log(event.toElement.id)
}
</script>