我想设计一个名为“ JavaScript Code Drills”的网站,在该网站上,用户会收到有关类似面试问题的编码提示,并可以编写经过有效性测试的解决方案。这将全部在前端完成。所以我需要某种方式

<script>
var f;
</script>
<div class="prompt">
   <p>Write the body of a function whose one parameter is an array and returns the maximum element of the array (If the array is empty, return undefined).</p>
</div>
<div class="solution">
    function ( arr )
    {
       var max = arr.length > 0 ? arr[0] : undefined;
       for ( var i = 1; i < arr.length; ++i ) if ( arr[i] > max ) max = arr[i];
       return max;
    }
</div>


然后,以某种方式使变量f等于#solution的内容作为JS代码。这种转换可能吗?

最佳答案

这有帮助吗?如果对您不起作用,我会改善的:)

为了简单起见,我更改了HTML。有关eval()功能的更多信息,请参见http://www.w3schools.com/jsref/jsref_eval.asp



window.addEventListener('load',function(){
  var f = document.getElementById('solution').innerHTML;
  eval(f);
});

<div class="prompt">
  <p>Write the body of a function whose one parameter is an array and returns the maximum element of the array (If the array is empty, return undefined).</p>
</div>
<div id="solution">
  alert('testing');
</div>

关于javascript - 是否可以将文本(innerHTML)转换为JavaScript代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34113279/

10-08 22:28
查看更多