JavaScript访问DOM元素并在该元素中运行JavaScript

时间:2015-03-16 12:51:27

标签: javascript

我正在尝试完成以下操作。由于某些环境/系统要求,它需要以这种方式完成。

我有这种元素:

<body> ....
<script type="disabled" id="1" class="someclass" >
  console.log("fire this");
</script>
...
</body>

我希望能够将元素的类型更改为&#34; text / javascript&#34;然后在脚本中执行代码。

例如:

<script type="text/javascript">

var el = document.getElementById("1");
el.setAttribute("type", "text/javascript");

...execute code within el if some precondition.....
</script>

可以这样做吗?

2 个答案:

答案 0 :(得分:0)

看看eval()。它应该能够做你想做的事。

答案 1 :(得分:-1)

简单的方法是:
在函数中添加代码。如果条件已满,则调用该函数。如下所示:

&#13;
&#13;
function do_something(){
    alert("function called");
    /* Your code goes here... */
}
var a=2;
if(a==2){
    do_something();
}
&#13;
&#13;
&#13;