getElementById()返回null,尽管元素存在。

3
我是Web编程新手(JSP,JavaScript等)。我正在动态创建复选框,然后在它们上应用JavaScript。问题是document.getElementById(..)总是返回null。我知道这个问题已经被问过很多次了,我尝试了那些解决方案,但不知为何它们对我没起作用,可能是我使用方法不对。以下是我的代码:
//window.onload = function handleUnusedDieFunctions(checkboxid) {
function handleUnusedDieFunctions(checkboxid) {

    console.log("checkbox id: " + checkboxid);
    var id = checkboxid;
    var chkd = document.getElementById(checkboxid.toString());
    console.log(chkd);
    alert("Just a formality");
    if(chkd.checked) {
       alert("checked");    
    }
    else {
        alert("unchecked");
    }
}

<!-- Some portion of jsp code -->

<div .....
out.println("<table>");
if((die.getFunctionList() != null) && (!die.getFunctionList().isEmpty())){
    functionListForDie = die.getFunctionList();
    ListIterator li11 = functionListForDie.listIterator();
    Function f1;
while (li11.hasNext()) {
f1 = (Function)li11.next();
System.out.println("IC: " + ic.getID() + " Die: " + die.getID() + ", Func: " +
                       f1.getID() + "\n");
out.println("<tr>");
    out.println("<td style='width:30px;'>");
if(unusedIcDieList.size() != 0)
{
    Boolean sameDie = false;
    Boolean sameFunc = false;
    for(IcDie icdie: unusedIcDieList)
    {
    if((icdie.getDieID() == die.getID()))
    {
        sameDie = true;
        System.out.println("icdie.getDieID() == " + icdie.getDieID() + 
                                   " , die.getID() == " + die.getID());
        ArrayList<Integer> unusedFunctionsList = icdie.getUnusedFunctions();
        for(Integer func: unusedFunctionsList)
        {
        System.out.println("Checking func = " + func + ", f1.getID() = " + f1.getID() );
        if(func.intValue() == f1.getID().intValue()) {
            System.out.println("func == " + func + " , f1.getID() == " + f1.getID());                                                                                                       
            sameFunc = true;
         }
    }

}
}
System.out.println("Same Die: " + sameDie.toString() + " , Same Func: " + sameFunc.toString() + "\n");
if(sameDie && sameFunc) {
    String id="test_" + String.valueOf(count);
    System.out.println("Should print unchecked checkbox for id: " + id);
%>
<input type="checkbox" name="unusedfunction" class="standard_checkbox" 
     style="margin: 0px 12px 0px 0px;"  id="'<%=id%>'"           click="handleUnusedDieFunctions('<%=id%>')" ><br>
   <%
}
else {
    String id="test_" + String.valueOf(count);
    System.out.println("Should print checked checkbox for id: " + id);
%>
<input type="checkbox" name="unusedfunction" class="standard_checkbox" style="margin: 0px 12px 0px 0px;" 
    id="'<%=id%>'" onclick="handleUnusedDieFunctions('<%=id%>')" checked="checked" ><br>
<%

}
 }
else
{
%>
<input type="checkbox" name="unusedfunction" class="standard_checkbox" style="margin: 0px 12px 0px 0px;" 
    id="'<%=id%>'" onclick="handleUnusedDieFunctions('<%=id%>')" checked="checked" ><br>
<%
}
count++;

发生的情况是,我可以在日志和第一个警报中看到文本框id,但document.getElementById(...)返回null。 我尝试将函数放在{{link1:window.load}}之后,但当我这样做时,我甚至没有获得第一个警报,并在控制台上获得这些错误。
TypeError: checkboxid is undefined
var chkd = document.getElementById(checkboxid.toString());

ReferenceError: handleUnusedDieFunctions is not defined
handleUnusedDieFunctions('test_1')

我知道在JSP页面中混合Java代码不是一个好主意,但这段代码不是由我编写的,我只需要添加一些功能,但是在某个时候必须修复它。

请问我做错了什么?

谢谢。


1
在 "var chkd = document.getElementById(checkboxid.toString());" 中执行 toString 的目的是什么? - Flasz
我需要知道哪些“复选框”未被选中,因为稍后我需要对数据库进行一些更改。 - uyaseen
1个回答

1
请在这个语句中删除 .toString():var chkd = document.getElementById(checkboxid.toString());,然后看看是否能够访问输入标签。或者您可以尝试像这样使用标签名称访问输入标签:document.getElementsByTagName('input')[0],这将使您可以访问第一个输入标签。
编辑:
对于动态生成的元素,我们可以使用addEventListener。您所需添加的是一个包装器div标签。我已经更新了jsFiddle:jsfiddle.net/giri_jeedigunta/NG3cP,并加入了一个包装器div标签,请查看一下。这适用于所有动态添加的元素。

谢谢您的回复,但这两个解决方案都不起作用 :/ - uyaseen
我已在jsFiddle上设置了类似的功能:http://jsfiddle.net/giri_jeedigunta/NG3cP/ 请查看一下。它可以正常工作,无论是否使用.toStrong()。另外,我想请求您检查HTML并查看所需的ID是否被正确填充和传递。 - giri-jeedigunta
非常感谢:),如果您有静态元素(在页面加载之前知道元素的数量),它可以工作,但问题是当您有动态元素(元素的数量取决于从数据库检索到的某个值)时,现在JavaScript不会按预期应用。我总是得到'chkd'的null值。我已经查看了HTML并且似乎是正确的,因为我可以在日志中看到'checkboxid',但document.getElementById(checkboxid)仍然返回null。 - uyaseen
1
对于动态生成的元素,我们可以使用addEventListener。你所需要添加的只是一个包装器div标签。我已经更新了jsFiddle:http://jsfiddle.net/giri_jeedigunta/NG3cP/,请看一下。这在所有动态添加的元素上都能完美地工作。我找到了另一个jsFiddle,在那里元素是动态添加的:http://jsfiddle.net/founddrama/ggMUn/通过https://dev59.com/L2Yq5IYBdhLWcg3wui0z - giri-jeedigunta
非常感谢,它起作用了,你真的救了我的一天 :)如果您可以,请编辑答案,这样我就可以将其标记为“已接受”。 - uyaseen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接