在javascript中使用原型

时间:2010-12-20 20:15:00

标签: javascript jquery prototype

我已经在我的javascript中定义了几个函数,它们可以很好地工作,但是当我把它放在原型中时,它似乎不起作用。

wall.html:

<script type="text/javascript" src="Jquery/jquery-1.4.4.js"> </script>
<script type="text/javascript" src="src/CommentManager.js"> </script>
<script type="text/javascript" src="src/Reply.js"> </script>
<script type="text/javascript" src="src/Comment.js"> </script>
<script type="text/javascript">
    $(document).ready(function(){
        CommentManager();
        $("form#newMessage").submit(function(){
            var message = $("input#newMessageTxt").val();
            var newComment = new Comment(message);
        });
    });
</script>
</head>

<body>
    <div class="message">
        <form id="newMessage"&gt;>
            <input type="text" id="newMessageTxt" height="200px" value="Write a message" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;" />
            <input type="submit" value="Submit" ></button>
        </form>
    </div>
</body>

但奇怪的部分是当我在googlechrome中运行调试工具时,$(“form#newMessage”)。submit完全没有调用。因此,永远不会创建Comment(消息)(这是我设置原型函数的地方)

Comment.js:

function Comment(message){
    var self = this;
    var message = message;

    var comment = document.createElement("li");
    comment.id = "comment";
    comment.textContent = message;
    //empty reply field
    var replyField = document.createElement("ul");
    replyField.id = "replyField";
    //create the appropriate buttons
    createButtons(comment);
    //append the replyField
    comment.appendChild(replyField);
    //insert into wall
    addComment(comment);
    //effect after insertion
    Effect(comment);
    $(comment).mouseleave(function() {mouseOut(comment);});
    $(comment).mouseenter(function() {mouseOver(comment);});
    return comment;
}
Comment.prototype={
    deleteComment : function (comment){
        $(comment).fadeOut();
        setTimeout(function() {comment.parentNode.removeChild(comment);},500);
    },
//there are more methods here
}

Commentmanager.js:

function CommentManager(){
    var owner = null; 

    var wall = document.createElement("ul");
    wall.id = "wall";

    document.body.appendChild(wall);
    return wall;
}

function addComment(comment){
    var wall = document.getElementById("wall");
    wall.appendChild(comment);
}

1 个答案:

答案 0 :(得分:0)

createButtons在哪里定义? (在Comment.js中)?

另外,你将最后一个文件标题为Commentmanager.js,但是wall.html有CommentManager.js(注意wall.js中的大写字母M)。我假设在SO问题中这是一个拼写错误,但要确保服务器上的文件名与html脚本标签匹配。