我想使用javascript更改newtab的内容。在我的manifest.json中我有这个
"chrome_url_overrides": {
"newtab": "index.html"
}
然后在我的index.html中我有
<script src="jquery.js"></script>
<script src="script.js"></script>
<body>
<h1>hello world</h1>
</body>
然后在我的script.js中,$('h1').remove()
没有触发任何内容。为什么?当我尝试console.log($)
它有效时。
答案 0 :(得分:0)
只要Chrome将<script>
标记插入DOM树,您的代码就会立即运行。
到那时,<h1>
还没有呢。
有两种解决方案;一种是简单地将<script>
标记移动到您引用的节点下面。
另一个更好的解决方案是使用一个事件,说“好的,DOM树已经完成,你现在可以使用节点”。使用jQuery,它将是the ready
event:
$(document).ready(function() {
/* your code here */
});
或者,缩短,
$(function() {
/* your code here */
});