用元素替换内联JavaScript函数调用

用元素替换内联JavaScript函数调用,javascript,html,Javascript,Html,这样的事情可能吗 <head> <script language="javascript"> function createElement(this) { var ele = document.createElement('div'); ele.setAttribute('style', 'display: inline-block; width: 100px; height: 20px; background: rgb(35,150,215);');

这样的事情可能吗

<head>
<script language="javascript">
function createElement(this) {
    var ele = document.createElement('div');
    ele.setAttribute('style', 'display: inline-block; width: 100px; height: 20px; background: rgb(35,150,215);');
    ele.setAttribute('onclick', 'alert(\'Yay!\');');
    this.replaceWith(ele);
}
</script>
</head>

<body>
blah blah blah some text <script language="javascript">createElement(parentTag);</script> blah blah more text.
</body

函数createElement(this){
var ele=document.createElement('div');
ele.setAttribute('样式','显示:内联块;宽度:100px;高度:20px;背景:rgb(35150215);');
ele.setAttribute('onclick','alert(\'Yay!\');');
此。替换为(ele);
}
废话废话一些文本createElement(parentTag);废话,废话,更多的文字。

然后你可能想使用
文档。改为写
。可能是@bfavareto Wow的重复,这似乎太明显了。只是其中的一件事,我不经常用它来思考。谢谢这看起来很乱。为什么不把逻辑和标记分开呢?在html中创建一个按钮,在css中添加样式,并在必要时使用JavaScript添加/删除类或事件。您当前的代码最终将成为一个需要维护的噩梦。但是可以避免document.write,请查看建议的重复链接@elclanrs我相信OP正在寻找一个脚本块,它可以被第三方插入到身体的任何地方,并在那里插入一些元素。