This right here is no bueno:(这里的权利不是布宜诺斯艾利斯:)
<script>
function test( ){
alert("Hiya buddy!");
}
document.getElementById().innerHTML = test();
</script>
document.getElementById()
requires you pass it the ID of an element.(document.getElementById()
要求您向其传递元素的ID。) So, for example, if there's a div
on the page with the ID of #alert
, you'd do document.getElementById('alert')
.(因此,例如,如果页面上有一个ID为#alert
的div
, #alert
执行document.getElementById('alert')
。)
You also can't assign a function to the inner HTML of an element.(您也不能将函数分配给元素的内部HTML。) You need to create a script
element and then append it to the document or another element.(您需要创建一个script
元素,然后将其附加到文档或其他元素。) Instead, try:(相反,请尝试:)
<script>
let myTest = document.createElement('script')
myTest.text = `
function test() {
alert('Hiya buddy!')
};
test();
`
const body = document.querySelector('body')
body.appendChild(myTest)
</script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…