我有一个页面,其中有多个启用图像上传的表单。表单是动态添加的,所以我不能使用不同的 ID。我想触发单击“更改”上的提交按钮,因此当用户单击所选文件的选择按钮时。一切正常,但我似乎不能只针对当前的形式。这是我到目前为止所拥有的
表格
<form id="my_uploader" name="my_uploader">
<label><?php __('Select Files:', 'cvf-upload'); ?> </label>
<label class="fileContainer">Upload files <input accept="image/*" class="input-button" multiple name="files[]" type="file"></label>
<input class="btn-upload" type="submit" value="Upload">
</form>
Jquery
$("body").on("change", "#my_uploader", function() {
$(this).find(".btn-upload").click();
});
目前,这会触发所有表单,而不仅仅是所需的表单。
最佳答案
如果您保留 id 并按类引用元素会怎么样?
此外,我相信我无法向您澄清它不起作用的原因是 onchange
您需要的事件需要绑定(bind)到 <input type="file">
而不是表单本身。
这是因为您实际上打算在从中选择至少一个文件之后捕获事件
<input accept="image/*" class="input-button target" multiple name="files[]" type="file">
记住取消注释实际命令。
$(this).closest('form').
寻找第一个<form>
从内到外 this 元素的父元素。
我们现在位于 <form>
的根部所以我们...
.find(".btn-upload")
最后...
.click();
在上面。
// Event binding for dynamically created elements
// Generally placed outside document.ready
$(document).on( 'change' , '.target' , function (event) {
console.log( 'Handler for .change() called.' );
//$(this).closest( 'form' ).find( '.btn-upload' ).click();
console.log( $( this ).closest( 'form' ).find( '.btn-upload' ).val() + ' button clicked.' );
});
// Event binding for document.ready elements
$( '.target' ).change(function() {
console.log( 'Handler for .change() called.' );
//$(this).closest( 'form' ).find( '.btn-upload' ).click();
console.log( $( this ).closest( 'form' ).find( '.btn-upload' ).val() + ' button clicked.' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label class="fileContainer">Upload files
<input accept="image/*" class="input-button target" multiple name="files[]" type="file">
</label>
<input class="btn-upload" type="submit" value="Upload">
</form>
关于javascript - this.find 无法按预期使用多种表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49343468/