pasar parámetro de cadena en una función onclick


Me gustaría pasar un parámetro (es decir, una cadena) a una función Onclick. Por el momento, hago esto:

'<input type="button" onClick="gotoNode(' + result.name + ')" />'

Con result.name por ejemplo, igual a la cadena "Add". Cuando hago clic en este botón, tengo un error que dice que Agregar no está definido. Dado que esta functioncall funciona perfectamente con un parámetro numérico, asumo que tiene algo que ver con los símbolos "" en la cadena. ¿Alguien tuvo este problema antes?

Author: Consec, 2012-03-10

18 answers

Parece que estás construyendo elementos DOM a partir de cadenas. Solo tienes que añadir algunas citas alrededor result.name:

'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'

Realmente deberías hacer esto con métodos DOM adecuados.

var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
    gotoNode(result.name);
});

​document.body.appendChild(inputElement);​

Solo tenga en cuenta que si se trata de un bucle o algo así, result cambiará antes de que se inicie el evento y tendrá que crear una burbuja de ámbito adicional para sombrear la variable cambiante.

 265
Author: david,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-31 10:34:26

Sugiero no usar controladores HTML onclick, y usar algo más común como document.getElementById.

HTML:

<input type="button" id="nodeGoto" />

JavaScript:

document.getElementById("nodeGoto").addEventListener("click", function() {
    gotoNode(result.name);
}, false);
 22
Author: mc10,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-02 00:09:04

Un par de preocupaciones para mí con respecto al uso de string escape en onClick y a medida que el número de argumentos crezca, se volverá engorroso de mantener.

El siguiente enfoque tendrá un clic de un salto: lleve el control a un método de controlador y el método de controlador, basado en el objeto de evento, puede deducir el evento de clic y el objeto correspondiente.

También proporciona una forma más limpia de agregar más argumentos y tener más flexibilidad.

<button type="button" 
        className="btn btn-default" 
        onClick="invoke" 
        name='gotoNode' 
        data-arg1='1234'>GotoNode</button>

En javascript capa:

  invoke = (event) => {
    let nameOfFunction = this[event.target.name];
    let arg1 = event.target.getAttribute('data-arg1');
    //We can add more args as needed...
    window[nameOfFunction](arg1) 
    //hope function is in window. 
    //Else the respective object need to be used 
    })
  }

La ventaja aquí es que podemos tener tantos argumentos (en el ejemplo anterior, data-arg1, data-arg2....) según sea necesario.

 17
Author: Sairam Krish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-18 09:06:27

Supongo que estás creando un botón usando JavaScript. Por lo tanto, el error en su código es que, se renderizará en esta forma

<input type="button" onClick="gotoNode(add)" />'

En este estado actual, add se considerará como un identificador como variables o llamadas a funciones. Usted debe escapar el valor como este

'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'
 16
Author: Starx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-10 02:42:34

Esta es una forma agradable y ordenada de enviar valor u objeto.

<!DOCTYPE html>
<html>
<body>
<h1  onclick="test('wow',this)">Click on this text!</h1>
<script>
var test =function(value,object){  
object.innerHTML=value;
};     
</script>
</body>
</html>
 10
Author: zokaee hamid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-30 15:57:21

Parámetro múltiple:

   bounds.extend(marker.position);
        bindInfoWindow(marker, map, infowindow,
     '<b>' + response[i].driver_name + '</b><br>' + 
     '<b>' +moment(response[i].updated_at).fromNow() + '</b>
      <button onclick="myFunction(\''+response[i].id+'\',\''+driversList+'\')">Click   me</button>'
    );
 5
Author: Zahid Rahman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-07 05:41:03

Editado: Si el requisito es hacer referencia al objeto global (js) en su código HTML, puede probar esto. [No use comillas ('o ") alrededor de la variable]

Fiddle referencia.

Javascript:

var result = {name: 'hello'};
function gotoNode(name) {
    alert(name);
}

HTML:

<input value="Hello" type="button" onClick="gotoNode(result.name)" />​
 4
Author: Sandeep G B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-10 02:33:30

Prueba Esto..

HTML:

<button id="a1" type="button" onclick="return a1_onclick('a1')">a1</button> 

JavaScript:

<script language="javascript" type="text/javascript">
    function a1_onclick(id) {
        document.getElementById(id).style.backgroundColor = "#F00";   
    }
</script>

Nota: asegúrese de enviar argumentos entre signos '' como ('a1') en código html

 4
Author: Mawardy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-23 20:32:40

También se usa el símbolo de acento grave ( ' ) en la cadena

Intenta:

`<input type="button" onClick="gotoNode('${result.name}')" />`

Para obtener más información, visite MDN y Stackoverflow

Por Chrome,Edge,Firefox (Gecko),Opera,soporte de Safari,pero no es compatible con Internet Explorer.

 2
Author: MJ Vakili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:42

Si su botón se genera dinámicamente:

Puede pasar parámetros de cadena a las funciones de javascript como el siguiente código:

Pasé 3 parámetros donde el tercero es un parámetro de cadena espero que esto ayude.

var btn ="<input type='button' onclick='RoomIsReadyFunc("+ID+","+RefId+",\""+YourString+"\");'  value='Room is Ready' />";

//your javascript function

function RoomIsReadyFunc(ID, RefId, YourString)
{
  alert(ID);
  alert(RefId);
  alert(YourString);
}
 2
Author: Mehdi Jalal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-27 10:38:40

Puede pasar refrence o string value simplemente ponga la función dentro de las comas doube "" asp debajo de snapshot

introduzca la descripción de la imagen aquí

 1
Author: Ayaat Shifa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-24 07:04:04

Para pasar múltiples parámetros puede convertir la cadena concatenándola con el valor ASCII como, para comillas simples podemos usar '

var str= "&#39;"+ str+ "&#39;";
 1
Author: Mr-Tc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-21 19:03:56

Para pasar múltiples parámetros puede convertir la cadena concatenándola con el valor ASCII como, para comillas simples podemos usar &#39;

var str= "&#39;"+ str+ "&#39;";

El mismo parámetro se puede pasar a la onclick() event.In la mayoría de los casos funciona con todos los navegadores.

 0
Author: PVIJAY,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-06 04:58:17
    <style type="text/css">
        #userprofile{
              display: inline-block;
              padding: 15px 25px;
              font-size: 24px;
              cursor: pointer;
              text-align: center;
              text-decoration: none;
              outline: none;
              color: #fff;
              background-color: #4CAF50; //#c32836
              border: none;
              border-radius: 15px;
              box-shadow: 0 9px #999;
              width: 200px;
              margin-bottom: 15px;

        }
        #userprofile:hover {
            background-color: #3e8e41
        }
        #userprofile:active {
              background-color: #3e8e41;
              box-shadow: 0 5px #666;
              transform: translateY(4px);
        }
        #array {
                border-radius: 15px 50px;
                background: #4a21ad;
                padding: 20px;
                width: 200px;
                height: 900px;
                overflow-y: auto;
            }

    </style>
if(data[i].socketid!=""){
$("#array").append("<button type='button'  id='userprofile' class='green_button' name="+data[i]._id+" onClick='chatopen(name)'>"+data[i].username+"</button></br>");                    
                }else{
                    console.log('null socketid  >>', $("#userprofile").css('background-color')); 
                    //$("#userprofile").css('background-color','#c32836 ! important');


$("#array").append("<button type='button'  id='userprofile' class='red_button' name="+data[i]._id+" onClick='chatopen(name)'>"+data[i].username+"</button></br>");  
                $(".red_button").css('background-color','#c32836');             
                }
 0
Author: Jay Jariwala,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-31 13:16:03

Si usar para la generación del juego de los botones con los parámetros diferentes de los handlers. https://www.w3schools.com/js/js_function_closures.asp

let some_button = document.createElement( "button" );
some_button.type = "button";

some_button.onclick = doWithParam( some_param );

function doWithParam( param ){
   return function(){
      alert( param );//<------Your code here
   }
}

Si lo hacemos:

some_button.onclick = foo( some_param );
function foo( param ){
    alert( param );
}

Luego la función foo comienza después de cada página de actualización.

Si lo hacemos:

for( let i = 0; i < 10; ++i ){
    var inputElement = document.createElement('input');
    inputElement.type = "button"
    inputElement.addEventListener('click', function(){
        gotoNode(result.name);
    });

​   document.body.appendChild(inputElement);​
}

Luego, para todos los botones creados en el bucle, el último valor del parámetro "result.name"

 0
Author: Александр Боярчук,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-05 06:01:15

Aquí hay una solución de Jquery que estoy usando.

[2]} Jquery
$("#slideshow button").click(function(){
    var val = $(this).val();
    console.log(val);
});

HTML

<div id="slideshow">
    <img src="image1.jpg">
    <button class="left" value="back">&#10094;</button>
    <button class="right" value="next">&#10095;</button>
</div>
 0
Author: DamianToczek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-27 05:15:41

Puede usar este código en el archivo JavaScript para agregar el botón:

<button class="btn btn-danger" onclick="cancelEmployee(\''+cancelButtonID+'\')" > Cancel </button>
 -1
Author: SHUJAT MUNAWAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-11 13:59:08

Lo siguiente funciona para mí muy bien,

<html>
<head>
    <title>HTML Form</title>
</head>
<body>
    <form>
        <input type="button" value="ON" onclick="msg('ON')">
        <input type="button" value="OFF" onclick="msg('OFF')">
    </form>
    <script>
        function msg(x){
            alert(x);
        }
    </script>
</body>
</html>
 -1
Author: Sayan Shankhari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 08:29:41