简体   繁体   English

如何在字符串中编写javascript函数

[英]How to write a javascript function inside a string

I'm trying to run a JavaScript function in R. One part of the code requires me to pass a JavaScript function containing a filename as a string. 我正在尝试在R中运行JavaScript函数。代码的一部分要求我传递一个包含文件名作为字符串的JavaScript函数。 Because the string contains a file path this leads to all hell breaking loose with single and double quotes and backslashes. 因为字符串包含一个文件路径,这导致所有地狱都被单引号和双引号和反斜杠破坏。 Here is what I have 这就是我所拥有的

d3chart$chart(tooltipContent = "#! function(item, x, y, e,z){ 
   return '' + '<img src=\"/Users/cBl.png\"' + '/>'
          } !#")
d3chart

The result should be that I can see an image in a tooltip on a chart. 结果应该是我可以在图表上的工具提示中看到图像。 The whole thing runs without error, but on the chart I get a question mark instead of the image which I guess means it cant follow the filename path. 整个过程运行没有错误,但在图表上我得到一个问号而不是图像,我猜这意味着它不能遵循文件名路径。 I think this is because I'm not sure how to write this filepath string properly to call the img src part. 我想这是因为我不确定如何正确编写这个文件路径字符串来调用img src部分。

I guess its the line break that causing the whole string to be syntax error, also I would remove the return ''+ it has no meaning I added the full path to the file location so you will be able to debug in order to get better understanding if that a wrong file location issue 我猜它的断行导致整个字符串是语法错误,我也会删除返回''+它没有意义我添加了文件位置的完整路径所以你将能够调试以便更好了解是否存在错误的文件位置问题

you can add \\n\\ to end of line: 你可以添加\\ n \\到行尾:

d3chart$chart(tooltipContent = "#! function(item, x, y, e,z){ \n\
   return '<img src=\"'+document.location.hostname+'/'+document.location.pathname+'/Users/cBl.png\"' + '/>'\n\
          } !#")
d3chart

有点难以确切地知道你的目标是什么,因为javascript有点乱,但这应该工作:

d3chart$chart(tooltipContent = "#! function(item, x, y, e,z) { return '<img src=\'/Users/cBl.png\' />' } !#")

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

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