开发者

Storing whole code in a variable -- Javascript

开发者 https://www.devze.com 2023-03-09 02:41 出处:网络
I want to store javascript code in a javascript variable. To explain clearly, please consider example:

I want to store javascript code in a javascript variable. To explain clearly, please consider example:

<html>
<body>

<script type="text/javascript">
<!--

    fu开发者_Python百科nction toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>

<a onclick="toggle_visibility('1');toggle_visibility('2');">Click here to toggle visibility of element </a>
<div id="1">This is 1</div>
<div id="2">This is 2</div>

<script type="text/javascript">
//document.getElementById('2').style.display='none';
</script>

</body>
</html>

Now suppose all this code is in a variable as a string or something. (i want to do this because i am exporting file to another html page where the code should get copied.) I used all variables such as using \ before ' and so on. referring to http://www.w3schools.com/js/js_special_characters.asp


Store like this: var myFunc = function(){ do stuff }

Run like this: myFunc();


To interpret JS code you need to use the JS function eval()

 var code = "alert('Ok')";

 eval(code);

Here is why using eval() is a bad idea:

Why is using the JavaScript eval function a bad idea?


Maybe try something like this:

var quoteElement = document.getElementById('2');
var quote = quoteElement.value;

// or even ..
var quote = document.getElementById('2').value;

You would now have the text value of your element in a variable.

0

精彩评论

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