我有以下文件上传策略,在文件输入中单击按钮时会触发单击事件,但无法监听触发的单击事件。能够听到以编程方式触发的点击的最佳方法是什么
$('#add-attachment').on( 'click', function(e) {
e.preventDefault();
var $fileList = $('#file-list'), attachementMarkup = '<li><input type="file" class="file"><span class="remove"></span></li>';
$(attachementMarkup).find('input[type="file"]').trigger('click');
//get the value of triggered file input
$('body').on('click', 'input.file', function() {
console.log($(this).val());
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add-attachment">Add files</button>
<ul id="file-list"></ul>
答案 0 :(得分:0)
有问题:
您尝试调用的<link href="https://fonts.googleapis.com/css?family=Lobster"
rel ="stylesheet" type="text/css">
<style> /* Why doesn't this work? */
h1 {
font-family: Lobster;
font-size: 50px;
color: red;
}
</style>
<body>
<h1> This is the h1 text which should be formatted.</h1>
</body>
input.file
事件在 之后被连接。将点击事件处理程序移到另一个点击事件处理程序之外(不要嵌套事件处理程序)
您的body.on(单击)不会触发,因为您的文件输入未附加到正文
出于浏览器安全原因,控制台日志将为空白,具体取决于浏览器
click
// get the value of triggered file input
$('body').on('click', 'input.file', function() {
console.log($(this).val());
})
$('#add-attachment').on('click', function(e) {
e.preventDefault();
var fileList = $('#file-list');
var attachementMarkup = '<li><input type="file" class="file"><span class="remove"></span></li>';
var li = $(attachementMarkup).appendTo(fileList);
li.find('input[type="file"]').trigger('click');
})
答案 1 :(得分:-1)
$('#add-attachment').on( 'click', function(e) {
e.preventDefault();
var $fileList = $('#file-list'), attachementMarkup = '<li><input type="file" class="file"><span class="remove"></span></li>';
$(attachementMarkup).find('input[type="file"]').click();
//get the value of triggered file input
$('body').on('click', 'input.file', function() {
console.log($(this).val());
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add-attachment">Add files</button>
<ul id="file-list"></ul>