jQuery.trigger('click') does not work in my code
I want the file explorer to pop up for user selecting files when user click a button which is a <input id="J_upload_btn" type="button" />
.
However the source above only works well on Firefox 4. On Chrome 11/12 and Firefox 3, the selecting-file-box pops up only after you click the button several times. My jQuery开发者_如何学Python version is 1.5.2.
$('#J_upload_btn').click(function() {
var _id = new Date().getTime(),
_$form = $('#J_pic_form'),
_$input = $('<input id="' + _id + '"' +
' type="file" name="file" class="hide_input">');
_$form.append(_$input);
_$input.trigger('click');
}
});
- Unmatched closing curly brace. Just removing it should work.
- You cannot reliably access DOM elements before the DOM tree is created. If this code is not wrapped in a function and called after that is the case, simply wrapping it in
$(function(){ /* code */ });
is enough for jQuery to call it as soon as the DOM is ready. - In some browsers (including Firefox 3), triggering click events on
<input type="file">
elements is restricted for security reasons.
This code works for me in Chrome:
$(function() {
$('#J_upload_btn').click(function() {
var _id = new Date().getTime(),
_$form = $('#J_pic_form'),
_$input = $('<input id="' + _id + '"' +
' type="file" name="file" class="hide_input">');
_$form.append(_$input);
_$input.trigger('click');
});
});
This kind of input is more restricted than others, by security issues. Sure there's a more current method, but the most common method to do this is using an invisible input (with opacity 0, not display:none), and placing a fake button over it, so when you click on the fake button, you're also clicking on the invisible input.
You may want to try not wrapping the input as a jayesh object. If you pass the HTML string to append, then the browser should add a new input field too.
var input = "<input id='"+id+"' />";
_$form.append(input);
Also, have you tried debugging the click in a console to make sure that it is getting fired or the subsequent code has the issue?
If you are tiggering click on the input, a function is expected to run. But as far as I can see, you have not written any function for the click event of _$input.
精彩评论