简体   繁体   中英

Add jQuery to dynamic JS-DOM objects

I'm creating several DOM-Objects with plain JavaScript which are placed into the page after everything is done.

Now I'd like to add some different functionality by using jQuery. And add it during the process of creation.

As it looks now (plain old, without any jQuery):

var mainput = document.createElement("textarea");
mainput.setAttribute("ID", "masseinfo_" + dsatz.ID);
mainput.setAttribute("onkeyup", "checkAndSendMaAjax(" + dsatz.ID + ", '" + masseinfoup + "', '" + dsatz.Typ + "', this.value)");

Using jQuery with keyup seems to fail as the object is not on the page yet.

mainput.keyup(debounce(250, function (e) {
    console.log('It works!');
    checkAndSendMaAjax(" + dsatz.ID + ", '" + masseinfoup + "', '" + dsatz.Typ + "', this.value);
}));

Error : keyup is not a function Using on is not much different.

mainput.on('keyup',null,(debounce(250, function (e) {
    console.log('It works!');
    checkAndSendMaAjax(" + dsatz.ID + ", '" + masseinfoup + "', '" + dsatz.Typ + "', this.value);
})));

Error : on is not a function

Searching a bit brought me to that page which wrote a bit about the usage of on instead of live:

$(".postitem").live("click", function() {...});

... would now be...

$(document).on("click", ".postitem", function() {...});

So I tried:

$(document).on('keyup',mainput,(debounce(250, function (e) {
        console.log('It works!');
        checkAndSendMaAjax(" + dsatz.ID + ", '" + masseinfoup + "', '" + dsatz.Typ + "', this.value);
    })));

Which is not generating an error, but doesn't do anything at all. What am I doing wrong?

$.on() function 2nd argument is a string (selector) and not a DOM Element. Change the code to use the selector "#masseinfo_" + dsatz.ID or mainput.getAttribute("id")

$(document).on('keyup', mainput.getAttribute("id"),(debounce(250, function (e) {
    console.log('It works!');
    checkAndSendMaAjax(" + dsatz.ID + ", '" + masseinfoup + "', '" + dsatz.Typ + "', this.value);
})));

jQuery on function

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