无法使用document.getElementById

时间:2015-07-13 20:54:39

标签: javascript php html css

我的代码有一个奇怪的问题,我正在使用Javascript更改某些div的背景颜色,但" document.getElementById"找不到div并返回NULL。

使用Javascript:

function colorFill(id)
{
   console.log(id); // Shows the correct string (r1h1)
   var divID = document.getElementById(id);
   // Even if I replace the id by "r1h1", directly the name of the div, it shows NULL
   console.log(divID); // Shows NULL
}

" id"是一个来自php函数的字符串,有效,因为当我尝试alert(id)时,它会正确显示(r1h1),但当我尝试使用" id"找到div时,它返回NULL。此外,我试图找到其他div,它也是如此。

这里是div:

HTML:

<?php
    include 'models/ms_model.php';
    if (isset( $_SESSION['gameState'] ) && !empty( $_SESSION['gameState'] ))
    { 
        fillGameTable();
    }
?>

<div id="row1" class="Row rowActive">
    <div id="r1h1" class="hole" style="float:left"></div>
</div>

我在这里调用Javascript函数:

PHP:

function fillGameTable()
{
    echo '<script src="views/js/ms.js"></script>';
    foreach($_SESSION['gameState'] as $ID)
    {
       echo'<script>colorFill("'.(string)$ID.'");</script>';
    }
}

最奇怪的是,我有另一个函数找到相同的div并且它有效,这个函数有问题......

2 个答案:

答案 0 :(得分:1)

您正在文档中的div之前输出colorFill()函数。您必须切换该顺序,以确保在调用colorFill()JS函数之前文档中的所有元素都已就位,如下所示:

<div id="row1" class="Row rowActive">
    <div id="r1h1" class="hole" style="float:left"></div>
</div>
<?php
    include 'models/ms_model.php';
    if (isset( $_SESSION['gameState'] ) && !empty( $_SESSION['gameState'] )){ fillGameTable(); }
?>

另一种选择是重构代码,以便fillGameTable()PHP函数返回在文档就绪事件中执行的javascript。

答案 1 :(得分:0)

If you are calling the JavaScript function from PHP make sure you're quoting the argument for the function properly:

function colorFill(id)
{
   var divID = document.getElementById(id);
   console.log(divID);
}

colorFill(r1h1); // not a string, returns null
colorFill('r1h1'); // string, returns object

It is likely you have something like this in PHP:

echo "colorFill(" . $variable . ")";

What you need is this (note the inclusion of the quotes surrounding the argument):

    echo "colorFill('" . $variable . "')";