我想在没有 jQuery
的情况下绑定(bind) input
和 select
更改。
目前我在 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/