简体   繁体   English

字符串中带有2个参数的Javascript函数

[英]Javascript function with 2 parameter inside string

How to insert multiple parameter inside javascript function inside string. 如何在字符串内的javascript函数内插入多个参数。

Example: 例:

var a = '<a onclick="my_function(parameter1, parameter2)">Click</a>';

i tried using 我尝试使用

my_function(\''+parameter1+', '+parameter2+'\')

but not working. 但不起作用。

Thanks all 谢谢大家

As you are using jQuery create elements using it and also bind event using it. 当您使用jQuery时,使用它创建元素,并使用它绑定事件。 Here in example I have used .data() to store arbitrary value which can be fetched in the click handler 在示例中,我使用.data()存储可以在点击处理程序中获取的任意值

var a = $('<a>Click</a>')
        .data('parameter1', parameter1)
        .data('parameter2', parameter2)
        .on('click', function(){
            var parameter1 = $(this).data('parameter1');
            var parameter2 = $(this).data('parameter2');
            my_function(parameter1, parameter2)
        });

For immediate problem, you need to escape quotes properly 对于当前问题,您需要正确地转义引号

var a = '<a onclick="my_function(\''+ parameter1 + '\',\'' parameter2 + '\')">Click</a>';

As per comment parameter1 is a number you don't need to wrap it. 根据comment parameter1是一个数字,您不需要将其包装。

var a = '<a onclick="my_function('+ parameter1 + ',\'' parameter2 + '\')">Click</a>';

Why not: 为什么不:

var a = document.createElement('a');
a.innerHTML = "Click";
a.onclick = function(p1, p2) { ... your code here }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM