简体   繁体   中英

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?

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() . You can use attribute selector with starts with wild card to bind event to elements having ids like ele*

$('#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 .

Besides what @adil mention,which is the correction to your error, you tagged the question with jquery so you could do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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