[英]onclick in html image tag - pass string value to javascript function
Code: 码:
// inside for loop.. //在for循环内
$("#tabs").append('<li><a href="#tab' + 1 + '">' + 1 + '</a><img src="/Images/pdf.png" onclick="test('1s')" /></li>');
function test(val) {
alert(val);
//return false;
}
Please see this code onclick="test('1s')"
. 请查看此代码onclick="test('1s')"
。 Is there any syntax wrong?. 有语法错误吗? I am not able to pass the value 1s
to the test
function. 我无法将值1s
传递给test
功能。
But I can pass the value if it is 1
instead of 1s
. 但是我可以传递值,如果它是1
而不是1s
。
UPDATE : 更新 :
How to pass a variable value...Lets say 1s
is in variable val
.. If I put onclick="test(\\'val\\')"
, I am getting the val
as "val" instead of 1s
如何传递变量值...假设1s
在变量val
。如果我将onclick="test(\\'val\\')"
放进去,我将val
改为“ val”而不是1s
SOLUTION: 解:
I solved myself..Refer to https://stackoverflow.com/a/32945494/5409139 我解决了自己.. 请参阅https://stackoverflow.com/a/32945494/5409139
您应该转义单个qoutes: '
带有\\
符号。
$("#tabs").append('<li><a href="#tab' + 1 + '">' + 1 + '</a><img src="/Images/pdf.png" onclick="test(\'1s\')" /></li>');
The code is in a single-quoted string argument, so the ''
around 1s
take you out of the string and back to the argument of the append
function call. 该代码是在一个单引号字符串参数,所以''
周围1s
带你出去的字符串和回的论点append
函数调用。 Try test(\\'1s\\')
(backslashes before each quote mark) instead. 尝试使用test(\\'1s\\')
(每个引号之前的反斜杠)。
More details of JavaScript strings are, eg, here . JavaScript字符串的更多详细信息在例如此处 。
This is simple bug. 这是简单的错误。 Please do following... 请执行以下操作...
$("#tabs").append("<li><a href='#tab" + 1 + "'>" + 1 + "</a><img src='/Images/pdf.png' onclick=\"test('1s')\" /></li>");
function test(val) {
alert(val);
}
I got the solution. 我找到了解决方案。 I added the quotes accordingly. 我相应地添加了引号。
var val = "1s";
$("#tabs").append('<li><a href="#tab' + 1 + '">' + 1 + '</a><img src="/Images/pdf.png" onclick="test(\'' + val + '\')" /></li>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.