【问题标题】:Can't get load() to work on img无法让 load() 在 img 上工作
【发布时间】:2016-06-03 13:00:45
【问题描述】:

在我开始之前,我知道这可能是重复的。我查看了以下解决方案:

jQuery .load() not working on my image

并更改了我的代码。但是我仍然无法启动负载。我已经尝试将 .load 更改为 .on('load' ...) 并基本上扼杀了我的代码以使其正常工作......我仍然无法让 alert() 触发......有什么想法吗?

<html>
   <head>
   <title>XXX</title>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
   </head>
   <body>
      <div id="outter">
         <div id="selectionBox">
                <form id="qqqq" enctype="multipart/form-data" action="/" method="post">
<input id="fileSelect" onchange="readURL(this);" type="file" name="imagePP" accept="image/x-png, image/gif, image/jpeg, image/bmp">
             </form>
         </div>
      </div>
   </body>
   <script>  
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    if (!$("#aaa").length)
                        $("body").append("<img id=\"aaa\">");

                    $("#aaa").attr('src', e.target.result);
                };
                reader.readAsDataURL(input.files[0]);
            }
        }

        $(document).ready(function() {
            $("#aaa").load(function() {
                alert("sdffds");
            }).each(function() {
                if (this.complete) {
                    $(this).trigger('load');
                }
            });
        });
   </script>
</html>

【问题讨论】:

  • 因为您在将图像添加到页面之前附加了事件处理程序。
  • ids 必须是唯一的。看起来您正在使用多次。不是确切的问题。但这不是一个好习惯。
  • Rejith 我没有看到任何 id 重复?哪一个?
  • 嗨 Epascarello,我认为即使动态添加带有 id 的元素,它仍然会被拾取?

标签: javascript jquery


【解决方案1】:

不确定,但在调用 document.ready() 时,您的图像标签应该绑定到文档。 readURL() 函数不会从任何实际创建 img 标签的地方调用。

【讨论】:

  • 抱歉,我在编辑时错过了 行。请立即查看
  • 查看下面的代码 - document.body.addEventListener( 'load', function(event){ var elm = event.target; if( elm.id === 'my_img'){/ / 或任何其他过滤条件 // 做一些事情 } }, true // 捕获事件 );
  • 已在以下线程中回答 - stackoverflow.com/questions/27332423/…
【解决方案2】:

试试

$(document).on("load", "#aaa", function() {

作为将load 事件绑定到#aaa 的一种方式 这样,动态添加的 #aaa 元素仍然可以将事件绑定到它们。

编辑: https://jsfiddle.net/4b8340gu/ 请查看此 jsFiddle,对您的代码稍作更改以使其正常工作。

我已将 .load 声明放在 readURL 中。

【讨论】:

    猜你喜欢
    • 2015-04-14
    • 1970-01-01
    • 2011-12-30
    • 2018-03-25
    • 2012-01-18
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多