简体   繁体   English

document.getElementById返回null

[英]document.getElementById returns null

I'm trying to write an extension for Chrome at the moment. 我目前正在尝试为Chrome开发扩展程序。

What I'm trying to do right now is create an HTML form that has a button on it which, when pressed, shows a message box. 我现在想做的是创建一个HTML表单,上面带有一个按钮,当按下该按钮时,它将显示一个消息框。

My project consists of an HTML file and a JavaScript file. 我的项目包含一个HTML文件和一个JavaScript文件。

<html>
<head>
<style>
body {
  width:100px;
  font-family: sans-serif;
  font-size: 0.8em;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<input id="buttonid" type="button" value="try it"></input>
</body>



chrome.tabs.onCreated.addListener(onCreated());

function myFunction()
{
alert("Hello World!");
}

function onCreated()
{
    var fld = document.getElementById("buttonid");
    if(fld==null)
    {
        alert("null");
    }
    else
    {
        alert("not null");
    }   
}

So my understanding is, when the HTML is rendered it runs my onCreated() function. 所以我的理解是,当呈现HTML时,它将运行我的onCreated()函数。 This then looks for an element with ID="buttonid". 然后,它将查找ID =“ buttonid”的元素。 But it is ALWAYS returning null, so a message box comes up saying "null". 但这总是返回null,因此出现一个消息框,显示“ null”。

Can anyone explain this? 谁能解释一下? This seems to make no sense. 这似乎没有任何意义。 I have tried running a slightly adapted version in IE but with identical results. 我尝试在IE中运行经过稍微调整的版本,但结果相同。

Just to be clear, I know this won't fulfil my description above but I am trying to access the button from the JavaScript before I attach an event to it. 只是要清楚一点,我知道上面的描述不符合我的描述,但是我尝试在将事件附加到JavaScript之前从JavaScript访问该按钮。

Replace 更换

chrome.tabs.onCreated.addListener(onCreated());

with

chrome.tabs.onCreated.addListener(onCreated);

Event handler rule #1: No parentheses! 事件处理程序规则1: 不加括号! - you do not want to execute the function, but register it. -您不想执行该功能,但要注册它。

Fixed! 固定! I placed window.onload=function(){onCreated()}; 我放置了window.onload = function(){onCreated()}; on the first line. 在第一行。 This means that when the html is loaded it runs my function "onCreated"... Thanks guys, you pushed me in the right direction. 这意味着在加载html时它将运行我的函数“ onCreated” ...谢谢大家,您向正确的方向推了我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM