Triggering change event on file input when invoked from javascript (ie headache)

梦想与她 提交于 2019-12-11 17:10:13

问题


I don't know what I'm doing wrong. I've found fixes/hacks for this but none of them seem to be working. Trying to use a single button/image (something) instead of the input-file control. It works so far except for in internet explorer. In ie the 'select file' dialog appears, lets you choose a file, the accompanying textbox gets populated but the change event doesn't fire. I've tried focus, blur, live, onpropertychange, change, onchange... but they just won't work. Any help?

jQuery:

      $(function() {
            var a = $('a.#LinkUpload');
            var f = $('input.#file');
            a.click(function() {
                f.click();
            });
            f.change(function() {
                alert('changed!');
            });
        });

html:

    <body>
    <form action="">
        <div>
            <a id="LinkUpload">Click Me!</a>
            <input type="file" id="file" name="file" />
        </div>
    </form>
</body>

回答1:


@Pointy said it. If it's an ID, you don't need to specify the tag name, so just do something like:

var $a = $('#LinkUpload'),
    $b = $('#file');

It's also a good practice to add a $ (dollar sign) in your variable names when you're caching a jQuery object, just so you know that a variable is actually a jQuery object.




回答2:


Here's a slightly cleaner implementation of the file part of Oppdal's solution:

f.bind(($j.browser.msie && $j.browser.version < 9) ? 'propertychange' : 'change',
       function(){ 
           alert('changed!');
       });



回答3:


It has been changed in the new jQuery version. I updated from 1.4.4 to 1.6.2 and it works fine without the workaround.




回答4:


Got it! (I think).

$(function() {
    var a = $('#LinkUpload');
    var f = $('#file');
    a.click(function() {
        f.click();
        setTimeout(function() {
            f.val(f.val());
        }, 1);
    });
    if ($.browser.msie && $.browser.version < 9) {
        f.bind('propertychange', function() {
            alert('changed');
        });
    } else {
        f.change(function() {
            alert('changed!');
        });
    }
});

Seems to work.



来源:https://stackoverflow.com/questions/5315528/triggering-change-event-on-file-input-when-invoked-from-javascript-ie-headache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!