在我的表单中,一组重复行(动态创建)中的每行都有一个按钮,允许用户上传文件,然后该文件将链接/绑定(bind)到该行中的数据。
head head upload
---- ---- --------
x y <button>
a b <button>
m n <button>
当单击任何一个按钮时,我显然可以轻松确定我所在的行。假设我位于 id="row_2"的行中。我在通过按钮单击调用的函数中具有该功能。
现在我调用$("#fileUploader").click()
以启动文件选择对话框。当用户选择一个文件并单击“确定”时,OnFileUploaderChange()
函数被自动调用。在该函数中,我获取了文件,现在我需要知道初始按钮来自 row_2,以便我可以将其与正确的行链接/关联。
摘要:OnButtonClick()
触发器OnFileUploaderClick()
这导致 OnFileUploaderChange()
才能自动触发。我的值是 OnButtonClick()
我需要在OnFileUploaderChange()
中提供它.
我怎样才能做到这一点?我如何获取我在 OnButtonClick()
中知道的值函数并使其在 OnFileUploaderChange()
中可用(将其传递给)当 OnFileUploaderClick()
时起作用函数在其间被调用。
我已经弄清楚如何将参数传递给 OnFileUploaderClick()
通过改变 $("#fileUploader").click()
来实现功能至$("#fileUploader").trigger('click', [ 2 ])
。但该参数仅在 OnFileUploaderClick()
内可用。我需要它 OnFileUploaderChange()
.
用户可能会启动上传一个大文件(当仍在上传时)会启动上传另一个较小的文件,以便多个线程同时上传。因此以任何方式使用全局变量都是行不通的 - 它必须是一个参数/参数以避免竞争条件和计时问题。
这里有一个 fiddle 可以帮助解释:https://jsfiddle.net/ho819tu0/1/
<小时/>编辑解决方案:
根据@vincent-d的评论和下面的答案(现在标记为正确),我已经修复了我的代码,这是另一个显示其工作原理的 fiddle : https://jsfiddle.net/sm2L9kt8/
最佳答案
问题是在初始气泡之外创建的任何 dom 对象和事件都不会被调用,并且这些事件/函数不会设置任何参数或全局变量
为了解决这个问题,jQuery 创建了一个非常好的函数,负责在这些实时创建的对象上创建新的调用
左侧赋值必须是包含 future “实时创建”对象的对象,右侧是引用这些对象的选择器
var colors=['green','yellow','blue'];
$('.add').click(function(){
let num=Math.floor(Math.random() * 3);
var newHtml='<td>line 1 <button class="clicker">click to set to <span>'+colors[num]+'</span></button></td>'
$('table tr').append(newHtml);
});
// click on add, it will set a new button, click on that button it will pass to this function because of the live event call
function colo(colorvar){
$('td').css('color',colorvar);
}
//this is the call, notice the body as left-hand, and .clicker button as right-hand
$('body').on('click','.clicker',function(){
// this refer to the element in the right-hand that is clicked (it can be a child, check at event target for more infos
colo($('span',this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='add'>ADD</button>
<table>
<tr>
<td>line 1 <button class='clicker'>click to set to <span>red</span></button></td>
</tr>
</table>
关于javascript - 如何将参数/参数传递给通过调用 click 以编程方式触发的 onchange 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58525666/