javascript - 在没有 jQuery 的情况下绑定(bind)输入并选择更改?

标签 javascript

我想在没有 jQuery 的情况下绑定(bind) inputselect 更改。

目前我在 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() 或任何其他的各种事件绑定(bind)方法, native中有.addEventListener()

所以你只需要将它们放在一起。抓取所有元素,遍历它们并绑定(bind)到它们中的每一个:

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 - 在没有 jQuery 的情况下绑定(bind)输入并选择更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22210877/

相关文章:

javascript - 根据组ID向d3可视化添加分页符

javascript - react map 以行渲染

javascript - 当请求的凭据模式为 '*' 时,响应中的 Access-Control-Allow-Origin' header 不得为通配符 'include'

javascript - 如何将一个对象分成更小的对象

javascript - 在 forEach 上通过引用传递

javascript - 与 json 一起调用 Javascript 函数

javascript - Moment JS - 对小时进行四舍五入并将输出限制为小数点后两位

javascript - ng-mouseover 不显示数据

javascript - NodeJS/Electron : Is it possible to register “STRG+<” as a globalShortcut and how can I do this?

JavaScript 对象 : is it not OK to redefine the prototype?