简体   繁体   English

.click函数中的$ .get

[英]$.get within a .click function

Not really sure where I'm going wrong with this one. 不太确定我在哪里出错了。 I have a button element that when clicked, I want the following script below to be triggered. 我有一个按钮元素,单击该按钮时,希望触发以下脚本。 No issues seemingly in Chrome when I click the button but the file isn't fetched. 当我单击按钮但未获取文件时,Chrome似乎没有问题。

Am I missing something silly in my .click? 我在.click中是否缺少一些愚蠢的东西?

  <script>
        $( "button" ).click(function() {
            $.get("testimg.php", function() {
                alert("Success!");
            });
        });
    </script>

Your code seems right. 您的代码似乎正确。 You need to make sure 2 things: 您需要确保两件事:

  1. testimg.php (with m) file exists in the same directory. testimg.php (带有m)文件存在于同一目录中。
  2. The <button> is in the DOM when the script runs. 脚本运行时, <button>位于DOM中。 I recommend using $(document).ready() event: 我建议使用$(document).ready()事件:

     <script> $(document).ready(function(){ $( "button" ).click(function() { $.get("testimg.php", function() { alert("Success!"); }); }); }); </script> 

Working jsFiddle 工作jsFiddle

Worth making it a jQuery.ajax call so you can trace errors. 值得将其jQuery.ajax调用,以便您可以跟踪错误。

$(function () {
  $("button").click(function(e) {
    e.preventDefault();
    $.ajax({
      url: "testimg.php",
      success: function () {
         alert("Success!");
      },
      error: function(x,y,z) {
        alert(z);
      }
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM