原型JS:Document.observe触发“未定义不是函数”错误

时间:2014-06-27 15:40:09

标签: javascript prototypejs

我尝试使用Prototype JS提供的Event.observe方法。为了确保加载DOM,我使用document.observe。这会导致错误未捕获的TypeError:undefined不是函数。正如您所见,原型JS已加载:

HTML

<!DOCTYPE html>
<html>
<head>
    <title>playground</title>
    <script language="javascript" type="text/javascript" src="../js/prototype.js"></script>
    <script language="javascript" type="text/javascript" src="../js/functions.js"></script>
</head>

<body>
    <div>
        <a href="#" id="meinLink">Hello World</a>
    </div>
    <input type="button" onclick="changeLinkText()" value="Change link by using Prototype">
</body>

的JavaScript

//this works
var changeLinkText = function(){
    $("meinLink").innerHTML="prototypeWorks";
};

//this causes the error
Document.observe("dom:loaded", function() {
    $("meinLink").observe('click', function(e) {
        document.getElementById('meinLink').innerHTML="prototypeDoesntWork";
    });
});

1 个答案:

答案 0 :(得分:2)

您的D

Document.observe("dom:loaded", function() {

是大写的,将其固定为正确的符号

document.observe("dom:loaded", function() {

可能会完成这项工作。

您还可以尝试invoke点击事件监听器。

$$('meinLink').invoke('on', 'click', '.item', function(event, el) {
    // el is the 'meinLink' element
});

只需使用on即可完成任务。

$("meinLink").on("click", function(event) {
   document.getElementById('meinLink').innerHTML="prototypeDoesntWork";
});