如何解析文本为JavaScript? [英] How to parse text as JavaScript?

查看:173
本文介绍了如何解析文本为JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题我的(目前没有答案),开车让我找到一个更好的解决方案,我正在尝试。



我的要求:



•没有 id

 <$ c可以任意添加到文档中的代码块$ c>< div class =thing> 
< elements ... />
< / div>

•对象被扫描并由外部脚本找到:

  var things = yd.getElementsBy(function(el){
return yd.hasClass('thing');
},null,document);

•对象必须单独配置,我目前是基于标识符的:

 < div class =thingid = thing0 > 
< elements ... />
< script type =text / javascript>
new Thing()。init({id:'thing0';});
< / script>
< / div>

•因此,我需要将标识符( id =thing0)进行排列,因此当多个相同代码块添加到页面时,没有重复的



•我仍然需要能够单独配置这些对象,没有标识符






SO!所有这一切都说,我想知道在每个添加的代码块的脚本块内创建一个动态全局变量,在其脚本标签中。当发现每个东西,我认为抓住脚本标签的innerHTML是合法的,并以某种方式将该文本转换为可用的JS对象。



讨论。好的,不要讨论,如果你喜欢,但如果你得到漂移,然后随意纠正我的思路或提供更好的解决方案 - 请!



d

解决方案

我明白你来自哪里,唯一的建议我可以给你这个是查看eval()标签。 eval()函数评估和/或执行JavaScript代码字符串。首先,eval()确定参数是否是有效的字符串,然后eval()解析查找JavaScript代码的字符串。如果它找到任何JavaScript代码,它将被执行。



所以你可以使用eval()标签来解析DIV或任何元素中的文本。对不起,我无法进一步帮助你。


This question of mine (currently unanswered), drove me toward finding a better solution to what I'm attempting.

My requirements:

• Chunks of code which can be arbitrarily added into a document, without an id:

<div class="thing">
  <elements... />
</div>

• The objects are scanned for and found by an external script:

var things = yd.getElementsBy(function(el){
    return yd.hasClass('thing');
},null,document );

• The objects must be individually configurable, what I have currently is identifier-based:

<div class="thing" id="thing0">
    <elements... />
    <script type="text/javascript">
      new Thing().init({ id:'thing0'; });
    </script>
</div>

• So I need to ditch the identifier (id="thing0") so there are no duplicates when more than one chunk of the same code is added to a page

• I still need to be able to config these objects individually, without an identifier


SO! All of that said, I wondered about creating a dynamic global variable within the script block of each added chunk of code, within its script tag. As each 'thing' is found, I figure it would be legit to grab the innerHTML of the script tag and somehow convert that text into a useable JS object.

Discuss.

Ok, don't discuss if you like, but if you get the drift then feel free to correct my wayward thinking or provide a better solution - please!

d

解决方案

I kind of understand where you are coming from and the only advice I can give you on this is to look into the eval() tag. The eval() function evaluates and/or executes a string of JavaScript code. First, eval() determines if the argument is a valid string, then eval() parses the string looking for JavaScript code. If it finds any JavaScript code, it will be executed.

So you could parse the text inside of a DIV or any element by using the eval() tag. Sorry I couldn't help you further.

这篇关于如何解析文本为JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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