我有一个打印出html页面的Perl脚本。 我想使用javascript来弹出警报消息。 警报消息在perl变量中定义为字符串。 我试图将perl变量值传递给javascript函数作为参数,但它不起作用。 请帮忙。
$perl_variable = "Welcome"; # alert msg print <<START <HTML> some html code.... <p>Click the button to wait 3 seconds, then alert "Hello".</p> <button onclick="myFunction('$perl_variable')">Try it</button> <script> function myFunction(var message){ setTimeout(function(){alert(message)},3000); } </script> </HTML> STARTI have a Perl script which prints out of html page. I want to use javascript to pop alert msg. The alert message is defined as string in the perl variable. I am trying to pass the perl variable value to javascript function as argument but it's not working. Please help.
$perl_variable = "Welcome"; # alert msg print <<START <HTML> some html code.... <p>Click the button to wait 3 seconds, then alert "Hello".</p> <button onclick="myFunction('$perl_variable')">Try it</button> <script> function myFunction(var message){ setTimeout(function(){alert(message)},3000); } </script> </HTML> START最满意答案
注意:这个答案的前半部分是指最初(编辑之前)出现在问题中的代码。
你需要:
使用正确的变量名称 生成JavaScript字符串文字(通过引用数据)这样:
myFunction('$perl_variable')请注意,如果您的数据可能包含JavaScript字符串文字中不允许的字符(例如新行),则字符串文字中具有特殊含义的字符(例如分隔它的引号)或具有特殊含义的字符在HTML中(例如分隔属性值的引号),您还需要执行适当的转义(分两步,首先是JS,然后是HTML)。
作为旁白, 你在JS中的函数定义也是错误的:
var关键字可能不在FormalParameterList中使用。 那应该是:
function myFunction(path){NB: The first half of this answer refers to the code that originally (before edits) appeared in the question.
You need to:
Use the right variable name Generate a JavaScript string literal (by quoting the data)Such:
myFunction('$perl_variable')Note that if your data might include characters that are not allowed in a JavaScript string literal (such as a new line), characters that have special meaning in a string literal (such as the quote mark that delimits it) or characters that have special meaning in HTML (such as the quote mark that delimits the attribute value) then you will also need to perform suitable escaping (in two steps, first for JS, then for HTML).
As an aside, your function definition in JS is also wrong:
The var keyword may not be used in the FormalParameterList. That should read:
function myFunction(path){更多推荐
发布评论