JavaScript 参数对象引用未知

javascript paramenter object reference unknown

本文关键字:未知 对象引用 参数 JavaScript      更新时间:2023-09-26

考虑以下代码(仅删除为相关代码):

.JS

function ToggleRow(objTwistie, objRow) {
  if (objRow.style.display == "none") {
    objRow.style.display = "";
    objTwistie.src = "../Images/SectionDown.gif";
  } else {
    objRow.style.display = "none";
    objTwistie.src = "../Images/SectionUp.gif";
  }
}

.HTML

<form method="post" action="./WelcomePage.aspx?Tab=2" id="form1">
  <table>
    <tr>
      <td>
        <table>
          <tr>
            <td>
              <img id="MyTwistie1" onclick="ToggleRow (MyTwistie1,SubRow1)" src="../Images/SectionDown.gif" alt="alt">&nbsp;
            </td>
            <td>
              <div><span onclick="ToggleRow (MyTwistie1,SubRow1)" style="font-size:13px"><b>Header Row</b></span></div>
            </td>
          </tr>
        </table>
      </td>
    </tr>
    <tr id="SubRow1">
      <td>
        This is the section that gets hidden
      </td>
    </tr>
  </table>
</form>

当我在 img 标记中调用 onclick 事件(单击页面上的图像)时,两个对象引用都正确传递给 ToggleRow 函数,并且脚本正常运行。

但是,当调用span onclick事件中的事件时,只有对objRow的引用正确传递,并且对MyTwistie1的引用会生成错误,指出"'MyTwistie1'未定义"。我意识到有更好的方法来做到这一点,但我只需要了解为什么这会失败。

编辑:使用getElementById的建议非常有效。如果有人可以通过自己传递 ID 来解释为什么它会失败,那就太棒了。

我建议在事件调用中用document.getElementById('MyTwistie1')替换MyTwistie1,用document.getElementById('SubRow1')替换SubRow1 onClick