为什么JavaScript不能在Chrome扩展中工作?
我正在使用HTML和JavaScript编写最简单的Chrome扩展,但显然JavaScript不起作用,我不知道为什么。以下是我的HTML代码:为什么JavaScript不能在Chrome扩展中工作?,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我正在使用HTML和JavaScript编写最简单的Chrome扩展,但显然JavaScript不起作用,我不知道为什么。以下是我的HTML代码: <script> function myFunction() { alert("I am an alert box!"); } </script> <input type="button" onclick="myFunction()" value="Show alert box"&
<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
<input type="button" onclick="myFunction()" value="Show alert box">
您的HTML DOCTYPE是过渡的吗?如果不是,您的代码可能更像:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<body>
<input type='button' value='Show alert box' onclick='myFunction()' />
<script type='text/javascript'>
function myFunction(){
alert('I am an alert box!');
}
</script>
</body>
</html>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<body>
<input type='button' value='Show alert box' id='btn' />
<script type='text/javascript' src='external.js'></script>
<script type='text/javascript'>
showAlert('btn');
</script>
</body>
</html>
后一种代码更易于重用,它将让您了解jQuery的
$()
。这是我的E()
函数更复杂的版本。弹出页面中不允许内联JS。我认为这是一件好事,不仅像Chrome宣称的那样安全,而且还迫使人们将结构和行为分开。重复的问题有一个解决问题的答案。一定要先搜索!:)
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<body>
<input type='button' value='Show alert box' id='btn' />
<script type='text/javascript' src='external.js'></script>
<script type='text/javascript'>
showAlert('btn');
</script>
</body>
</html>
function E(e){
return document.getElementById(e);
}
function showAlert(e){
E(e).onclick = function(){
alert('I am an alert box!');
}
}