【问题标题】:Use Loop in a JavaScript function在 JavaScript 函数中使用循环
【发布时间】:2019-11-19 02:33:28
【问题描述】:

晚上好。所以,你们能给我一些例子,说明我如何使用循环来使这个函数更小,我不熟悉 JS 中的循环。谢谢:)

function setValue(){

                let in1 = document.querySelector("#number1")
                let in2 = document.querySelector("#number2")
                let in3 = document.querySelector("#number3")
                let in4 = document.querySelector("#number4")
                let in5 = document.querySelector("#number5")
                let in6 = document.querySelector("#number6")
                let in7 = document.querySelector("#number7")
                let in8 = document.querySelector("#number8")
                let in9 = document.querySelector("#number9")
                let in10 = document.querySelector("#number10")

                setAttribute('marginLeft', in1.value)
                setAttribute('marginRight', in2.value)
                setAttribute('marginBottom', in3.value)
                setAttribute('marginTop', in4.value)
                setAttribute('margin', in5.value)
                setAttribute('paddingLeft', in6.value)
                setAttribute('paddingRight', in7.value)
                setAttribute('paddingBottom', in8.value)
                setAttribute('paddingTop', in9.value)
                setAttribute('padding', in10.value)
            }

【问题讨论】:

    标签: javascript function loops


    【解决方案1】:

    使用类而不是 ID,并有一个您需要设置的属性数组:

    function setValue() {
      const attributeNames = ['marginLeft', 'marginRight', 'marginBottom', ...];
      document.querySelectorAll('.numbers').forEach((elm, i) => {
        setAttribute(attributeNames[i], elm.value);
      });
    }
    

    如果你不能依赖现有的NodeList.forEach(它不是那么旧,所以在旧浏览器上不支持),首先填充它:

    if (!NodeList.prototype.forEach) {
      NodeList.prototype.forEach = Array.prototype.forEach;
    }
    

    (或将其更改为for 循环,或.call Array.prototype.forEach

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      相关资源
      最近更新 更多