首页 > 解决方案 > 如何在执行 document.getElementById 之前检查字段是否有值?

问题描述

这可能不是很复杂,但我不是贸易编码员,所以我确定我在这里遗漏了一些东西。

这是我到目前为止所拥有的。

function buildURL (){
          url = document.getElementById("url").value;
          source = document.getElementById("source").value; //required
          campaignId = '-_-' + document.getElementById("campid").value; //required
          brand  = '-_-' + document.getElementById("brand").value; //required
          brand2  = '-' + document.getElementById("brand2").value; //optional
          brand3  = '-' + document.getElementById("brand3").value; //optional
          medium  = '-_-' + document.getElementById("medium").value; //required
          product = '&cm_mmca1=" + document.getElementById("product").value; //optional

          if (url.includes('?')) {
              url = url + '&cm_mcc=';
          } else {
              url = url + '?cm_mmc=';
          }

          document.getElementById("fullURL").innerHTML = "URL: " + url + source + campaignId + brand + brand2 + brand3 + medium + product ;
       }

现在,url 部分效果很好。只要我在我创建的表单中的文本框中输入 URL,它就会打印到屏幕上,并在我进行更改时更新。问题来自我打印到屏幕上的附加值。执行每个变量的所有内容都会document.getElementById立即打印到屏幕上。这适用于必需变量,但不适用于可选变量。我认为解决方案是防止所有字段被传递,document.getElementById("fullURL").innerHTML除非字段中有值,但我不知道该怎么做。建议?

标签: javascript

解决方案


您需要检查每个选项值,如果该值不是空字符串,则为变量分配一个特殊值,否则只返回一个空字符串,对连接的最终 URL 没有影响:

function buildURL() {

    url = document.getElementById("url").value;
    source = document.getElementById("source").value; //required
    campaignId = '-_-' + document.getElementById("campid").value; //required
    brand = '-_-' + document.getElementById("brand").value; //required
    medium = '-_-' + document.getElementById("medium").value; //required

    // OPTIONAL VALUES: (Use trim() to ensure no white spaces affect our checks)

    const brand2Value = document.getElementById("brand2").value.trim();
    // ( brand2Value ) ? essentially works much like ( brand2Value !== "" ) ?
    brand2 = brand2Value ? '-' + brand2Value : ""; //optional

    const brand3Value = document.getElementById("brand3").value.trim();
    brand3 = brand3Value ? '-' + brand3Value : ""; //optional

    const productValue =  document.getElementById("product").value.trim();
    product = productValue ? '&cm_mmca1=' + productValue : ""; //optional

    if (url.includes('?')) {
        url = url + '&cm_mcc=';
    } else {
        url = url + '?cm_mmc=';
    }

    document.getElementById("fullURL").innerHTML = "URL: " + url + source + campaignId + brand + brand2 + brand3 + medium + product;
}

补充说明:

  • 函数变量(url, source,brand等)没有用 声明是否有原因var/let/const

确保始终使用 let 或 const 声明变量,否则它们将在全局范围内可用,这是我们在 JavaScript 中试图避免的事情。


推荐阅读