我想绑定inputselect更改而没有jQuery

目前我在jQuery中具有以下内容

$(':input').each(function(){
    $(this).attr('value', this.value);
});
$('select').each(function(){
    var Selected = $(this).children('option:selected');
    $(this).children('option').removeAttr('selected', false);
    Selected.attr('selected', true);
    $(this).replaceWith($(this)[0].outerHTML);
});
$(':input').bind('keyup', function() {
    $(this).attr('value', this.value);
});
$('select').change(function(){
    var Selected = $(this).children('option:selected');
    $(this).children('option').removeAttr('selected', false);
    Selected.attr('selected', true);
    $(this).replaceWith($(this)[0].outerHTML);
    $('select').unbind('change');
    $('select').change(function(){
        var Selected = $(this).children('option:selected');
        $(this).children('option').removeAttr('selected', false);
        Selected.attr('selected', true);
        $(this).replaceWith($(this)[0].outerHTML);
        $('select').unbind('change');
    });
});


jQuery如何完成?

最佳答案

这是一个了解jQuery快捷方式的本机等效项的问题。所以:

$(':input') //jQuery
document.querySelectorAll('input, select, textarea, button'); //native


对于jQuery的.bind().change().on()或其任何其他各种事件绑定方法,本机中有.addEventListener()

因此,您只需要将它们放在一起。抓住所有元素,遍历它们并绑定到每个元素:

var els = document.querySelectorAll('input, select, textarea, button');
[].forEach.call(els, function(el) {
    this.addEventListener('keyup', function() {
        //do something on key up
    }, false);
    if (el.tagName == 'SELECT') this.addEventListener('change', function() {
        //also do something on change for dropdowns
    }, false);
});

关于javascript - 绑定(bind)输入并选择没有jQuery的更改?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22210877/

10-12 07:39
查看更多