onMouseover函数不起作用,否则它会起作用

时间:2012-12-12 00:18:23

标签: javascript html

我有一个javascript函数,但如果我使用它,它不起作用。如果我在html上没有使用相同的代码,它确实有效。

<script type="text/javascript">
function jon(str) {
    id = 'j'+str;
    getElementById(id).setAttribute('class', '');
}
function jover(str) {
    id = 'j'+str;
    getElementById(id).setAttribute('class', 'hide');
}
</script>

<form id="lijst" action="" method="POST" onSubmit="return formOK();">
    <table>
        <tr onMouseOver="getElementById('jtitle').setAttribute('class', '');" onMouseOut="getElementById('jtitle').setAttribute('class', 'hide');">
            <th>* Title</th>
            <td><input type="text" name="title" /></td>
            <td id="jtitle" class="hide">Vul een film of serie titel in.</td>
        </tr>
        <tr onMouseOver="jon('type');" onMouseOut="jover('type');">
            <th>* Type</th>
            <td><select name="type"><option value="film">Film</option><option value="serie">Serie</option></select></td>
            <td id="jtype" class="hide"></td>
        </tr>

标题确实有效,但类型不起作用。 控制台说没有定义getElementById()。我试图将var id = ''用于函数,但这不起作用。

那我该怎么办?

1 个答案:

答案 0 :(得分:3)

您需要前缀document.

document.getElementById(id).setAttribute(...);

getElementById方法定义了document方法。要在任何对象上调用方法,您需要使用定义它的对象,然后使用点.和方法名称。例如:

document.getElementById()
   |    ^       |
   |            |
   |            |
[object]    [method]

唯一的例外是window对象,当您在其上定义函数或变量时不需要它;你可以使用它,就好像它是独立的。但实际上,所有全局变量都在窗口对象上。这可能是由于在创建变量时意外省略了var关键字。例如:

x = 5;

假设先前未定义变量x。由于使用x关键字创建的var ,因此将其放在window对象上。我们可以在控制台中查看它:

>> window.x;

 : 5

这可能会导致棘手的情况,因为它可能与外部作用域中声明的另一个x变量冲突。这就是为什么用var定义总是很重要的原因。没有理由不这样做。

相关问题