简体   繁体   English

如何执行作为字符串一部分的Javascript函数?

[英]How can I execute a Javascript function that is a part of a string?

I have a string called 'content' which contains HTML code. 我有一个名为“ content”的字符串,其中包含HTML代码。 When a user clicks a button, the innerHTML of a div is set to the value of content however, if the string contains a function, I would like to execute it. 当用户单击按钮时,div的innerHTML设置为content的值,但是,如果字符串包含函数,我想执行它。

Example: 例:

Function: 功能:

function state() {return "QLD";}

'content' string: “内容”字符串:

var content = "<div>Example text here</div><div><br></div><div>state()<br>/div>";

Current Output: 电流输出:

Example text here 示例文字在这里

state() 州()

Desired Output: 所需输出:

Example text here 示例文字在这里

QLD 昆士兰州

You can use the eval() function. 您可以使用eval()函数。

eval("2 + 2");             // returns 4

Of course, you'll have to figure out how to determine whether the string in your content contains a function and how to get just that string. 当然,您将必须弄清楚如何确定内容中的字符串是否包含函数以及如何仅获取该字符串。 Also, remember that eval() is evil (ie probably dangerous) with user content. 另外,请记住eval() )对用户内容是有害的(即可能是危险的)。

You can try to concatenate a variable in there... then load it like this 您可以尝试在其中连接变量...然后像这样加载它

var UI = {
  myLoad: () => {
     alert("works!");
  }
};


var myContent = "<span>" + UI.myLoad() + "</span>";

[Edited] [编辑]

 var UI = { myLoad: () => { return "QLD"; } }; var myContent = "<span>" + UI.myLoad() + "</span>"; myDv.innerHTML = myContent; 
 <div id='myDv'>&nbsp;</div> 

Using a template literal (also ECMAScript link ) you'd do: 使用模板文字 (也称为ECMAScript链接 ),您可以执行以下操作:

 function state(){return 'QLD'} var content = `<div>Example text here</div><div><br></div><div>${state()}<br>/div>`; console.log(content) 

But I don't know whether support for templates is sufficient for your purpose. 但是我不知道对模板的支持是否足以满足您的目的。

The latest convention is to use template literal (backticks) 最新约定是使用模板文字(反引号)

function state() {return "QLD";}

var content = `<div>Example text here</div><div><br></div><div>${state()}<br>/div>`;

console.log(content)

You can do this by checking for possible functions. 您可以通过检查可能的功能来做到这一点。 When you find that possible function, attempt to execute it and replace with what the function returns. 找到可能的函数后,尝试执行该函数并替换为该函数返回的内容。 If the function does not exist, then just replace with what looked like a function. 如果该函数不存在,则只需替换为一个看起来像函数的函数即可。 In this case, you can pass a scope where the function may exist, in case it does not exist on the global scope. 在这种情况下,如果该函数不在全局范围内,则可以传递一个可能存在该功能的范围。

 function checkFunctions(html, scope) { return html.replace(/(\\w+)\\(\\)/g, function(match, capture) { try { return scope[capture](); } catch (e) { return match; } }); } function state() { return "QLD"; } var content = "<div>Example text here</div><div><br></div><div>state()<br></div>"; content = checkFunctions(content, this); document.getElementById('foo').innerHTML = content; 
 <div id="foo"></div> 

Where are you getting the content string? 您从哪里获得内容字符串? Can you change that? 你能改变吗? The better design would be to split the data up. 更好的设计是将数据拆分。 Here's an example... 这是一个例子

var content={
    html:'<div>Example text here</div><div><br></div><div id="jsContent"></div>',
    action:state
    actionTarget="jsContent"
}

 document.body.innerHTML+=content.html;
document.getElementById(content.actionTarget).innerHTML=content.action();

If the content is coming from an ajax call then have your PHP or whatever send you a JSON string 如果内容来自ajax调用,则让您的PHP或其他任何东西向您发送JSON字符串

echo '{ "html":"<div id='jsContent'></div>", "action":"state", "actionTarget":"jsContent" }';

and then use JSON.parse to get the object 然后使用JSON.parse获取对象

 var content=JSON.parse(ajax.resonseText);

In this case you'll have to call the action differently 在这种情况下,您必须以不同的方式调用操作

window[content.action]();// all functions belong to the window unless you say other wise, replace window with wherever your function is if it is somewhere else

just replace your statements like this 像这样替换您的陈述

function state() {return "QLD";}
var content = "<div>Example text here</div><div><br></div><div>"+state()+"<br>/div>";

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

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