iScroll 4脚本-我如何才能让它不那么笨重

iScroll 4 script - how can I make this less bulky?

本文关键字:4脚本 iScroll      更新时间:2023-09-26


我对javascript很陌生,不知道该如何处理下面的脚本。

请参阅下面的脚本,这是我找到的一个资源,可以帮助我激活iscroll4…中的输入

var inputSubmit = document.getElementById('gform_submit_button_1');
inputSubmit.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);



这对于一个输入来说很好,但我也有一个完整的表单来应用它。所以我就是这样写的…

var inputSubmit = document.getElementById('gform_submit_button_1'),
    inputName = document.getElementById('input_1_1'),
    inputEmail = document.getElementById('input_1_2'),
    inputPhone = document.getElementById('input_1_3'),
    inputMessage = document.getElementById('input_1_4'),
    inputCaptcha = document.getElementById('input_input_1_5');
inputSubmit.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);
inputName.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);
inputEmail.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);
inputPhone.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);
inputMessage.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);
inputCaptcha.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);


变量可能很好,但有没有办法让我少写一些脚本,把底部组合成一个?

如果事情就是这样,那就不用担心了。

任何建议都会很有帮助。


感谢

var formInputs = [
  document.getElementById('gform_submit_button_1'),
  document.getElementById('input_1_1'),
  document.getElementById('input_1_2'),
  document.getElementById('input_1_3'),
  document.getElementById('input_1_4'),
  document.getElementById('input_input_1_5')
];
for(var i = 0; i < formInputs.length; i++) {
  formInputs[i].addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
  }, false);
}

或者你可以通过循环

formInputs.forEach(function(el) {
  el.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
  }, false);
});

或者。。(不推荐使用,因为:为什么在数组迭代中使用"for…in"是个坏主意?)

for(var el in formInputs) {
  el.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
  }, false);
}