2010-02-04 13 views
8

En esta página hay una manera de dynamic add html (textbox,input button and radio elements with javascriptAgregar evento al botón con javascript

mi questioon es ¿Cómo puedo añadir un evento para el botón, imagino que sólo quiero crear el botón, no el cuadro de texto o la radio elemento.

ACTUALIZACIÓN
Tengo problemas aquí ... Me han tratado algunas de las soluciones aportadas pero me causa problemas, voy a tratar de explicar ...

im tratando de abrir el archivo XML , léalo y cree un objeto html con las propiedades del xml, hasta ahora todo bien, pero si trato de agregar el evento, xmlObj cames null any ideias ??

tengo este ...

script = "function OnClientDragEnd(dock, args)" + 
         " {" + 
           "var hidd = document.getElementById('" + HiddenField1.Value + "');" + 
           "hidd.value = dock.get_id();" + 
        //"alert(hidd.value);" + 
           "var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');" + 
           "xmlDoc.async = 'false';" + 
           "xmlDoc.load('Config.xml');" + 
           "xmlObj = xmlDoc.documentElement;" + 
           "if (xmlObj.childNodes.length>0)" + 
           "{" + 
           " for (var i = 0; i < xmlObj.childNodes.length; i++)" + 
           " {" + 
           "  if (xmlObj.childNodes(i).getElementsByTagName('Id')[0].text == hidd.value){" + 
           "   var txtTb2 = document.getElementById('" + TextBox4.ClientID + "');" + 
           "   txtTb2.value = xmlObj.childNodes(i).getElementsByTagName('Titulo')[0].text;" + 
           "   y = xmlObj.childNodes(i).getElementsByTagName('Titulo')[0].nextSibling;" + 
           "   yy = xmlObj.childNodes(i).getElementsByTagName('Titulo')[0].previousSibling;" + 
        //"   alert(y.nodeName);" + 
           "   for(i=0;i<yy.text;i++){" + 
           "    alert('aa');" + 
           "    var tbox = document.createElement('input');" + 
           "    tbox.setAttribute('type', 'text');" + 
           "    tbox.setAttribute('value', y.text);" + 
           "    tbox.setAttribute('name', 'name');" + 
           "    var abcd = document.getElementById('spanObjDock');" + 
           "    abcd.appendChild(tbox);" + 
           "    var bt1 = document.createElement('input');" + 
           "    bt1.setAttribute('name', 'mais');" + 
           "    bt1.setAttribute('value', '+');" + 
           "    bt1.setAttribute('type', 'button');" + 
           "    bt1.onclick = function(){alert('Clicked!');};" + //--> this dont work 
           //"    bt1.setAttribute('Click','addRadioButton()');" + //--> and this dont work 
           "    abcd.appendChild(bt1);" + 
           "    var bt2 = document.createElement('input');" + 
           "    bt2.setAttribute('name', 'menos');" + 
           "    bt2.setAttribute('value', '-');" + 
           "    bt2.setAttribute('type', 'button');" + 
           "    abcd.appendChild(bt2);" + 
           "    var break1 = document.createElement('br');" + 
           "    abcd.appendChild(break1);" + 
           "    node = y;" + 
           "    y=y.nextSibling;" + 
           "   }" + 
           "   break; " +//<input type="button" onclick="" name"as" /> 
           "  }" + 
           " }" + 
           "}" + 
          "}";//+ 

Respuesta

14

Simplemente, el uso addEventListener método:

buttonRef.addEventListener("click", function() { 
    alert("Blah blah..."); 
}, false); 

(Tendrás que buscar una solución de navegador múltiple en Google). IE no es compatible con addEventListener)

Donde buttonRef es una referencia al botón. ¿Cómo puedes obtener esa referencia? Hay muchas formas de hacer eso. Puede usar document.getElementById() o cualquier otro método de esta "familia".

+0

¡Funciona! Tengo algunas dificultades, cualquier cosa que eventualmente agregué, recibí el error de que xmlObj era nulo, pero reinicio VS2008, cierro algunas ventanas y comienza a funcionar. ¡¡Gracias!! – SlimBoy

+0

Encontré este enlace que ayudó https://developer.mozilla.org/En/DOM:element.addEventListener – SlimBoy

+0

IE 9 realmente admite 'addEventListener' [ref] (http://stackoverflow.com/questions/6927637/addeventlistener -in-internet-explorer # 6927800). – another

5
var element = document.createElement("input"); 
element.onclick = function() {alert('Clicked!');}; 
+0

mala suerte! maldita sea, vencerme por un segundo ... ¡no debería haber puesto ese ejemplo extra! –

+0

En realidad, parece que la marca de tiempo es exactamente la misma para nuestras dos publicaciones. : D –

3

Probablemente el más fácil camino entre navegadores es establecer el nombre del evento como una propiedad del elemento:

Element.onclick = function() 
{ 
    // do something... 
} 
Element.onmouseup = function() 
{ 
    // do something else... 
} 
2

Tiene que adjuntar el nuevo evento al crear el elemento DOM.

Por ejemplo:

var e = document.createElement('input'); 
e.onclick = function() 
      { 
       alert('Test'); 
      }; 
Cuestiones relacionadas