问 题
我有一个ajax脚本,我试图从一个函数发布。我正在使用onlick href,但它不会出现未定义。这是使用wordpress。我试图在范围内外移动代码,但我似乎仍然无法使其工作。
lt; p id ="live"gt;
lt; p class ="container"gt;
lt;?php the_content(); ?gt;
lt; p id ="comment-display"gt;
lt; form method ="post"action ="index.php"id ="comments_submit"gt;
lt; input type ="hidden"id ="namebox"value ="lt;?php echo $ _session ['name']?gt;" name = "名称"/gt;
lt; input type ="hidden"id ="emailbox"name ="email"value ="lt;?php echo $ _session ['email'];?gt;"/gt;
lt; textarea id ="chatbox"placeholder ="提出问题或发表评论"name ="comment"class ="form-control"gt;lt; / textareagt;
lt; a href ="javascript:submitcomment();" type ="submit"id ="submit"name ="submit"class ="btn cardh-bg text-white text-bold margin-top-5"gt;提交评论lt; / agt;
lt; / formgt;
lt; br /gt;
lt; p id ="displaycomments"gt;lt; / pgt;
lt; / pgt;
lt; / pgt;
lt; / pgt;
lt; script type ="text / javascript"gt;
jquery(函数($){
setinterval(function(){
$ .ajax({
method:"get",
url:"lt;? php echo get_template_directory_uri()?gt; /get_chat.php"
})。done(function(html){
$('#displaycomments')。html(html);
}) ;
},2000);
函数submitcomment(){
$ .ajax({
method:"post",
url:"template -live.php",
data:{submitcomment:$('#chatbox')。val(),submitname:$('#namebox')。val(),submitemail:$('#emailbox') .val()}
})。done(function(html){
alert('你的评论已经提交,将在批准后显示。');
$('# chatbox')。val('');
});
}
});
lt; / scriptgt;
谢谢:)
解决方案
当你执行 javascript:submitcomment()时,它正在调用全局函数 submitcomment 。由于 submitcomment 是在 jquery(function($){...})函数中定义的,所以它不是全球化的。因此, window.submitcomment 是 undefined (因此 undefined不是函数)。
全局变量存储在窗口对象中。
因此,您可以将 submitcomment 公开为全局:
window.submitcomment = function(){...}
请注意,你应该尽量避免使用全局变量。在这种情况下,你可以通过添加:
$("#submit")。点击(submitcomment);
//在这种情况下,您不应再将submitcomment声明为全局
由于您处于某种形式,因此您希望在单击 a 元素时停止默认浏览器行为,方法是使用 return false 在函数结束时。