开发者

How to parse text as JavaScript?

开发者 https://www.devze.com 2023-01-03 17:47 出处:网络
This question of mine (currently unanswered), drove me toward finding a better solution to what I\'m attempting.

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 adde开发者_JS百科d 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.


Why not

<div class="thing virgin">
  <script>
    var newElems = yd.getElementsBy(function(el){
     return yd.hasClass(el,'thing') && yd.hasClass(el, 'virgin');
    },null,document );
    // find the 'virgin's and remove the 'virgin' class from them as you init?
  <script>
</div>

You could of course remove the <script> tag entirely if you are adding this element via javascript, and just execute the code on the elements you create.

0

精彩评论

暂无评论...
验证码 换一张
取 消