简体   繁体   中英

Create element with onInput event defined using jQuery?

I'm attempting to create a DOM element using jQuery. I would like to create this DOM element with an 'on input' event defined.

This works:

var headerInput = $('<input/>', {
    'class': 'headerInput',
    type: 'text'
});

headerInput.on('input', function() {
    backgroundManager.get('activePlaylist').set('title', $(this).val());
});

This does not:

var headerInput = $('<input/>', {
    'class': 'headerInput',
    type: 'text',
    input: function(){
        backgroundManager.get('activePlaylist').set('title', $(this).val());
    }
});

I was wondering why? I thought these two syntaxes were identical.

It says:

As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn) can be used as a property of the object passed to the second parameter.

but there is no such jQuery method input . Not for every event does an instance method exist.

You can use the on property as follows though:

var headerInput = $('<input/>', {
    'class': 'headerInput',
    type: 'text',
    on: {
        input: function(){
            backgroundManager.get('activePlaylist').set('title', $(this).val());
        }
    }
});

More info and examples can be found in the documentation .

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