我有一个ajax脚本,我正在尝试从一个函数发布。我正在使用 onlick href 但它不会显示为未定义。这是使用wordpress。我尝试过在范围内和范围外移动代码,但我似乎仍然无法让它工作。
<div id="live">
<div class="container">
<?php the_content(); ?>
<div id="comment-display">
<form method="post" action="index.php" id="comments_submit">
<input type="hidden" id="nameBox" value="<?php echo $_SESSION['name'] ?>" name="name"/>
<input type="hidden" id="emailBox" name="email" value="<?php echo $_SESSION['email']; ?>"/>
<textarea id="chatBox" placeholder="Ask a question or make a comment" name="comment" class="form-control"></textarea>
<a href="javascript:submitComment();" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>
</form>
<br />
<div id="displayComments"></div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(function($) {
setInterval(function(){
$.ajax({
method: "GET",
url: "<?php echo get_template_directory_uri()?>/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('');
});
}
});
</script>
谢谢:)
最佳答案
当您执行 javascript:submitComment()
时,将调用全局函数 submitComment
。由于 submitComment
是在 jQuery(function($) { ... })
函数中定义的,因此它不是全局的。因此,window.submitComment
是未定义
(因此undefined 不是一个函数
)。
全局变量存储在window
对象中。
因此,您可以将 submitComment
公开为全局:
window.submitComment = function () {...}
请注意,您应该尽可能避免使用全局变量。在这种情况下,您可以通过添加以下内容来做到这一点:
$("#submit").click(submitComment);
// In this case, you shouldn't declare submitComment as a global anymore
由于您处于表单中,因此您希望通过在函数末尾使用 return false
来停止单击 a
元素时的默认浏览器行为。
关于javascript - jquery onclick 函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44292763/