jquery onclick函数未定义

我有一个ajax脚本,我试图从一个函数发布。 我正在使用onlick href,但它不会出现未定义。 这是使用wordpress。 我试图在范围内外移动代码但我仍然​​无法让它工作。

<input type="hidden" id="nameBox" value="" name="name"/> <input type="hidden" id="emailBox" name="email" value=""/> Submit Comment

jQuery(function($) { setInterval(function(){ $.ajax({ method: "GET", url: "/get_chat.php" }).done(function(html){ $('#displayComments').html(html); }); }, 2000); function submitComment(){ $.ajax({ method: "POST", url: "template-live.php", data: {submitComment:$('#chatBox').val(),submitName:$('#nameBox').val(),submitEmail:$('#emailBox').val()} }).done(function(html){ alert('Your comment has been submitted, and will be displayed after approval.'); $('#chatBox').val(''); }); } });

谢谢 :)

当你执行javascript:submitComment() ,调用一个全局函数submitComment 。 由于submitComment是在jQuery(function($) { ... })函数中定义的,因此它不是全局的。 因此, window.submitComment undefined (因此undefined is not a function )。

全局变量存储在window对象中。

因此,您可以将submitComment公开为全局:

 window.submitComment = function () {...} 

请注意,您应该尽可能避免使用全局变量。 在这种情况下,您可以通过添加:

 $("#submit").click(submitComment); // In this case, you shouldn't declare submitComment as a global anymore 

并且由于您处于某种forms,因此您希望在单击a元素时停止默认浏览器行为,方法是在函数末尾使用return false

另外还有@Ionică Bizău的解决方案。

您可以使用onclick="submitComment()"而不是href。

  Submit Comment