以文本形式运行和显示代码,而无需重复 [英] Run and display code as text without repeating

查看:93
本文介绍了以文本形式运行和显示代码,而无需重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将javascript代码存储在一个对象中,然后在用户单击按钮时运行它的一部分.到目前为止,我有这个:

I want to store javascript code in an object, and then run parts of it when the user clicks a button. So far I have this:

var exampleCode = {
    test: "$('body').css('background: pink');"
}
$(document).ready(function(){
    console.log(exampleCode.test);
    exampleCode.test;
});

我有两个问题,第一个是如何使代码真正运行?

I have two questions, the first is, how to I get the code to actually run?

第二个是,如果我想在自己的javascript中包含一些html,该怎么办,就像下面的代码行一样:

The second is, what do I do if I want to have some html in my javascript, say like the following line of code:

$('body').append('<div class="whatever"></div>');

这不能与对象值周围的双引号一起使用.

This wont play well with the double quotes around the object value.

我所有这些的目标是能够在同一页面上以文本形式运行和显示代码,而无需两次编写代码,因此,如果您有其他建议,那将很棒.

My goal with all of this is to be able to both run and display code as text on the same page without having the code written twice, so if you have other suggestions, that would be great.

推荐答案

您不能敏锐地执行代码字符串",因此运行代码的唯一方法是执行以下操作:

You can't acually do a "string of code", so the only way to run you code is to do this :

var exampleCode = {
    test: function(){$('body').css('background', 'pink');}
}
$(document).ready(function(){
    console.log(exampleCode.test); //No "()" for the function
    exampleCode.test();
});

将函数保存在对象中,然后调用它.

You save a function in the object and the you call it.

如果要附加该函数的文本,可以执行以下操作:

If you want to append the text of the function, you can do this :

$('body').append(String(exampleCode.test))

这将附加功能,但是没有格式

This will append the function, however there is no formating

但是,您可以使用javascript函数.replace()进行一些格式化.

However, you can use the javascript function .replace() to do a little bit of formating.

//Really weak example, can be optimised
var txtCode = String(exampleCode.test)
txtCode = txtCode.replace(';', ';<br/>')
txtCode = txtCode.replace('{', '{<br/>')
txtCode = txtCode.replace('}', '}<br/>')
var code = $('<code/>').html(txtCode)
$('body').append(code)


其他信息:您可以使用"\"转义字符.


Additional information: You can escape character with "\".

执行alert('How\'s it?')会弹出警报"怎么样?",而alert("See that : \"!")会弹出警报"看到那个:!".

Doing alert('How\'s it?') will pop the alert "How's it?" and alert("See that : \"!") will pop the alert "See that : "!".

这篇关于以文本形式运行和显示代码,而无需重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆