change javascript html

change - JavaScript-onHaga clic para obtener la ID del botón pulsado



class html (14)

Cómo hacerlo sin JavaScript en línea

Generalmente se recomienda evitar el JavaScript en línea, pero rara vez hay un ejemplo de cómo hacerlo.
Esta es mi forma de adjuntar eventos a los botones.
No estoy del todo contento con cuánto tiempo más se compara el método recomendado con un simple atributo onClick .

Solo navegadores modernos

<!DOCTYPE html> <html> <head> <script> (function(doc){ var hasClass = function(el,className) { return ('' '' + el.className + '' '').indexOf('' '' + className + '' '') > -1; } 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>

Navegador cruzado

<!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>

Navegador cruzado con jQuery

<!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 función insertHTML no funciona en ella a pesar de que funciona en todos mis navegadores.

Siempre puede reemplazar insertHTML con document.write si no le importa sus drawbacks

<script> document.write(''<button class="click-me" id="btn1">Button 1</button>''); </script>

Fuentes:

¿Cómo encontrar la identificación del botón que se está haciendo 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() { }


(Creo que el atributo id debe comenzar con una letra. Podría estar equivocado).

Podrías ir a delegación de eventos ...

<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 modelo de eventos extravagantes.


Botón 1 Botón 2 Botón 3

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;


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


En general, las cosas son más fáciles de mantener organizadas si separa su código y su marca. Defina todos sus elementos y luego, en la 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. Por lo tanto, el identificador se referirá al elemento DOM en el que hizo clic. A continuación, 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>


Es necesario enviar el 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.id como clicked_id que puede usar en su función. Véalo en acción aquí.


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 hace que se haga clic en el ID de cualquier botón.

Si solo desea obtener el valor del botón pulsado en un lugar determinado, simplemente póngalos en un contenedor como

<div id = "myButtons"> buttons here </div>

y cambiar el código a: -

$(document).ready(function() { $(''.myButtons button'').on(''click'', function() { alert (this.id); }); });

espero que esto ayude


Si no desea pasar ningún argumento a la función onclick, solo use event.target para obtener el elemento pulsado:

<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); }


Simplemente puedes 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); }


USANDO PURE JAVASCRIPT: Sé que es tarde, pero puede ser útil para las personas del futuro:

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.


<button id="1"class="clickMe"></button> <button id="2" class="clickMe"></button> <button id="3" class="clickMe"></button> $(''.clickMe'').live(''click'',function(){ var clickedID = this.id; });


<button id="1" class="clickMe"></button> <button id="2" class="clickMe"></button> <button id="3" class="clickMe"></button> <script> $(''.clickMe'').click(function(){ alert(this.id); }); </script>


<button id="1" onClick="reply_click()"></button> <button id="2" onClick="reply_click()"></button> <button id="3" onClick="reply_click()"></button> function reply_click() { console.log(window.event.target.id) }


<button id="1" onClick="reply_click(this)"></button> <button id="2" onClick="reply_click(this)"></button> <button id="3" onClick="reply_click(this)"></button> function reply_click(obj) { var id = obj.id; }