简体   繁体   English

动态事件上的onchange事件

[英]onchange event on dynamically event

I am creating a input type file and the code is like this 我正在创建一个输入类型文件,代码是这样的

var ele=document.createElement("INPUT");
            ele.type="file";
            ele.id="ele"+i;
            $("#media").append("<br>");
            $("#media").append("<br>");
            $('#media').append(ele);
            $('#ele'+i).on('change',change());
function change()
{
     alert("hello");
}

the problem is that the hello gets alerted when the element is created , why? 问题是创建元素时,hello会收到警报,为什么?

This line is incorrect: 这行是不正确的:

        $('#ele'+i).on('change',change());

It should be: 它应该是:

        $('#ele'+i).on('change',change);

You were calling the function instead of passing the function as an argument. 您是在调用函数,而不是将函数作为参数传递。

But you shouldn't need to do this after you append each element. 但是,在附加每个元素之后,您无需执行此操作。 Give the new elements a class, and use event delegation: 给新元素一个类,并使用事件委托:

$("#media").on("change", ".file", change); // Do this just once
function change()
{
     alert("hello");
}

var ele=document.createElement("INPUT");
ele.type="file";
ele.className = "file"
$("#media").append("<br>");
$("#media").append("<br>");
$('#media').append(ele);

You are call method instead of passing handler name. 您是调用方法,而不是传递处理程序名称。

Change 更改

$('#ele'+i).on('change',change());

To

$('#ele'+i).on('change',change);

You can delegate event to parent using on() , you need to give event handler name ie change instead of calling it like change() . 您可以使用on()将事件委托给父对象,您需要提供事件处理程序名称,即change而不是像change()那样调用它。 You can use attribute selector with starts with wild card to bind event to elements having ids like ele* 您可以使用以通配符开头的属性选择器将事件绑定到具有ele*ids元素

$('#media').on('click', '[id^=ele]', change);

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. 委派事件的优势在于,它们可以处理来自后代元素的事件,这些事件在以后的时间添加到文档中。 By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery api . 通过选择保证在附加委托事件处理程序时会出现的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序jQuery api的需要

Besides what @adil mention,which is the correction to your error, you tagged the question with jquery so you could do 除了@adil提及的内容(这是对您的错误的更正)之外,您还使用jquery标记了问题,因此您可以

$('<input>', {
  type:'file',
  id: 'ele' + i,
  change: change
}).appendTo('#media');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM