【问题标题】:Reload captcha image重新加载验证码图片
【发布时间】:2016-09-30 22:12:20
【问题描述】:

我有一个 php 脚本,它生成一个带有验证码的 png 图像作为图像文本。

session_start();   
$captchanumber = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz'; 
$captchanumber = substr(str_shuffle($captchanumber), 0, 8); 
$_SESSION["code"] = $captchanumber; 
$image = imagecreatefromjpeg("cap.jpg");     
$black  = imagecolorallocate($image, 160, 160, 160);   
$font = '../assets/fonts/OpenSans-Regular.ttf';  
imagettftext($image, 20, 0, 35, 27, $black, $font, $captchanumber);   
header('Content-type: image/png');    
imagepng($image);
imagedestroy($image);

我想通过 jQuery 或 JavaScript 重新加载图像,所以我使用的是这样的:

$(document).ready(function(e) {
    $('.captcha').click(function(){
        alert('yolo');
        var id = Math.random();
        $(".captcha").replaceWith('<img class="captcha" src="img/captcha.php?id='+id+'" />');
        id ='';

    });
});

领域:

<img class="captcha" src="img/captcha.php">

作为第一次尝试,它有效,但之后如果我再次单击该字段,它将不再有效,我不知道为什么。

【问题讨论】:

    标签: javascript php jquery image


    【解决方案1】:

    您正在用新元素替换 dom 元素,它将破坏所有附加的事件处理程序。

    方法一:可以通过event delegation监听动态添加元素事件来解决。

    $(document).ready(function(e) {
        $('body').on('click', '.captcha', function(){
            alert('yolo');
            var id = Math.random();
            $(this).replaceWith('<img class="captcha" src="img/captcha.php?id='+id+'" />');
        });
    });
    

    $(document).ready(function(e) {
      $('body').on('click', '.captcha', function() {
        alert('yolo');
        var id = Math.random();
        $(this).replaceWith('<img class="captcha" src="img/captcha.php?id=' + id + '" />');
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img class="captcha" src="img/captcha.php">

    方法 2: 不用替换整个元素,只需用新的 url 更新 img src 属性即可。

    $(document).ready(function(e) {
        $('.captcha').click(function(){
            alert('yolo');
            var id = Math.random();
            $(this).attr('src', 'img/captcha.php?id='+id);
        });
    });
    

    $(document).ready(function(e) {
      $('.captcha').click(function() {
        alert('yolo');
        var id = Math.random();
        $(this).attr('src', 'img/captcha.php?id=' + id);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img class="captcha" src="img/captcha.php">

    方法3:你也可以用纯JavaScript来完成,和之前的逻辑一样。

    document.querySelector('.captcha').addEventListener('click', function() {
      alert('yolo');
      var id = Math.random();
      this.setAttribute('src', 'img/captcha.php?id=' + id);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img class="captcha" src="img/captcha.php">

    方法四:给元素设置onClick属性,用纯JavaScript处理点击事件,这里需要传递this作为参数来引用元素。

    function captcha(ele) {
      alert('yolo');
      var id = Math.random();
      ele.setAttribute('src', 'img/captcha.php?id=' + id);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img class="captcha" onclick="captcha(this)" src="img/captcha.php">

    【讨论】:

      【解决方案2】:

      您的代码只能运行一次的原因是带有验证码类的原始元素是replaced and the click is no longer detected

      解决方案

      一个干净的解决方案是替换图像的 src 而不是整个元素。

      Working example

      jQuery

        $(document).ready(function () {
              $("#changeThis").click(
                  function () {
                      changeImage();
                  }            
              );
          });
      
      function changeImage() {
         //we want whole numbers not numbers with dots here for cleaner urls
         var id = Math.floor((Math.random() * 1000) + 1);
         $('#changeThis').attr("src",'img/captcha.php?id='+id);
         //Not sure why you want to empty id though.
         id ='';
      }
      

      或单行:

      $("#changeThis").click($('#changeThis').attr("src",'img/captcha.php?id='+Math.floor((Math.random() * 1000) + 1)));
      

      HTML 对于唯一元素,使用 id="" 语法而不是 class="",当多个元素可以具有相同的类时使用类,id 是唯一元素的标识符。

      <img class="captcha" id="changeThis" src="img/captcha.php">
      

      【讨论】:

        【解决方案3】:

        可能只是将事件绑定到代码替换的元素的问题。请考虑将delegate binding 改为文档:

        // Replace
        $(document).ready(function(e) {
            $('.captcha').click(function(){
        // With
        $(document).ready(function(e) {
            $('.captcha').on('click', document, function(){
        

        【讨论】:

        • 根据api.jquery.com/on 此处的文档,您应该编写: $(document).on('click', '.captcha', function() { ... } )。稍后添加到文档中的元素作为第二个参数传递,反之亦然
        【解决方案4】:

        好的。问题是您声明了 id 变量,并尝试在第二个函数调用中重新声明它,此时已经存在 id 变量,因此它将被默默地忽略并使用空字符串。

        尝试将var id ='';移出函数,并在函数中使用id = Math.random()

        【讨论】:

        • 问题是他替换了具有直接绑定的完整元素,通过将其替换为函数不再有效的绑定,委托绑定将修复它。
        【解决方案5】:

        这是一个委托问题,因为你插入了一个新元素,所以移除了事件监听器,有很多解决方案:

        解决方案 1:

        使用内联事件绑定

        function rebindCaptcha()
        {
        var id = Math.random();
                $(".captcha").replaceWith('<img onclick="rebindCaptcha()" class="captcha" src="img/captcha.php?id='+id+'" />');
        }
        

        解决方案 2:

        将元素保留在 dom 中,只需更改 src 属性:

        $(document).ready(function(e) {
              $('.captcha').click(function(){
                  var id = Math.random();
                  this.src = 'img/captcha.php?id='+id+';
                  id ='';
        
              });
          });  
        

        仅供参考,jQuery 委托可以这样完成:

        $(".parent .child").on("event",function(){/*your handler here*/}) 
        

        $(".parent").on("event",".child",function(){/*your handler here*/})
        

        通常选择一个你确信它会一直存在于你的 dom 中的父级,并且总是在文档就绪事件之后附加监听器。

        【讨论】:

          【解决方案6】:

          对我来说,正如我所说,你必须在 javascript 中使用 id 来改变事物

          // reload is your button reload and captcha must be a div who surrounding the captcha img
          
          document.querySelector('#reload').addEventListener('click', function(e){
            var reload = document.getElementById('captcha')
            reload.innerHTML = "your new logic"
          })
          

          //reload.innerHTML 将成为新的验证码 html 代码

          【讨论】:

            【解决方案7】:

            为了使用新代码加载图像,您可以使用 captcha.php 的版本参数。请参阅以下代码。

            <img class="captcha" id="secure_code" src="img/captcha.php"> <a href="#" id="reload_captcha">Reload</a> 
            

             

            $(document).ready(function(e) {
                $('#relaod_captcha').click(function(e) {
                    e.preventDefault() ;
                    $('#secure_code').attr('src', "img/captcha.php?ver="+Math.random()) ;
                }) ;
            }) ;
            

            我希望它会有所帮助。

            【讨论】:

              猜你喜欢
              • 2012-12-17
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-05-01
              • 2023-03-08
              • 2011-02-19
              • 2016-01-11
              • 1970-01-01
              相关资源
              最近更新 更多