如何将文本解析为JavaScript

如何将文本解析为JavaScript

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

问题描述

这个问题



我的要求:


(我现在没有回答),让我寻找更好的解决方案。

•可以任意添加到文档中的大块代码,不包含 id

 < 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:50