【问题标题】:jquery onclick function not definedjquery onclick 函数未定义
【发布时间】:2017-11-01 17:31:39
【问题描述】:

我有一个 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>

谢谢你:)

【问题讨论】:

  • 为什么不使用事件处理程序而不是内联 JS?
  • 什么未定义为未定义,您为什么期待它?

标签: javascript jquery ajax wordpress


【解决方案1】:

当您执行javascript:submitComment() 时,这将调用全局函数submitComment。由于submitComment 是在jQuery(function($) { ... }) 函数中定义的,因此它不是全局的。因此,window.submitCommentundefined(因此是 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

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

【讨论】:

  • 谢谢你,成功了! :) 会尽可能投票。
  • @BrendonWells 不要忘记标记答案 :) 很高兴它解决了问题! :D
  • 你也可以把函数定义放在jQuery(function($) { ... })之外。函数定义不需要等到 DOM 加载完毕。
  • @Barmar 是的,但它确实使用来自回调的$ 函数。
【解决方案2】:

替代@Ionică Bizău 的解决方案。

你可以用onclick="submitComment()"代替href。

<a onclick="submitComment()" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<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 onclick="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);

    window.submitComment = function(){
      console.log('submitComment called!');
      $.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>

【讨论】:

  • 这行不通,因为submitComment 函数是在$(...) 回调中定义的。
  • @IonicăBizău 你是对的,我也必须使用window.submitComment = function()
  • @AravindhGopi 这是在学习!我也必须使用window.submitComment = function(),如果在$(...)中定义的函数
  • @DanielH Yeap :)
猜你喜欢
  • 2018-06-10
  • 2019-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多