开发者问题收集

JavaScript - 在 for 循环中调用函数时出错

2021-09-28
188

我有以下脚本,该脚本应该从 URL 查询字符串中获取参数,将它们放入数组中,然后将值放入文本字​​段中。

<script type="text/javascript">
    function getUtms(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    
    var utmArray = ['utm_campaign','utm_medium','utm_source'];
    for (var i = 0; i < utmArray.length; i++) {
      console.log(utmArray[i]);
      document.querySelector("p." + utmArray[i] + " input").value = getUtms(utmArray[i]);
    }
    </script>

    <input type="text" name="utm_campaign">
    <input type="text" name="utm_medium">
    <input type="text" name="utm_source">

但是我收到以下错误

Uncaught TypeError: Cannot set properties of null (setting 'value')

与行相关

document.querySelector("p." + utmArray[i] + " input").value = getUtms(utmArray[i]);

提前致谢!

2个回答

您需要查询 input 元素。在您的代码中,正如 @Reyno 指出的那样,您正在查询没有 value 属性的 p 标签。您还可以使用 getElementsByName 来通过当前索引处的指定名称访问每个输入的值。

您可以像这样重写您的代码:

function getUtms(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    
    var utmArray = ['utm_campaign','utm_medium','utm_source'];
    for (var i = 0; i < utmArray.length; i++) {
      console.log(utmArray[i]);
      document.getElementsByName(utmArray[i])[0].value = getUtms(utmArray[i]);
    }
<input type="text" name="utm_campaign">
<input type="text" name="utm_medium">
<input type="text" name="utm_source">
Matt Croak
2021-09-28

您需要的选择器不是 “ p。” + utmarray [i] +“输入” 反而 “ input [name =“+utmarray [i]+“]”

i.e。获取带有名称属性等于utmarray [i]

的输入标签

Tom P
2021-09-28