繁体   English   中英

如何在执行 document.getElementById 之前检查字段是否有值?

[英]How do I check to see if a field has a value before executing 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 ,除非该字段中有值,但我不知道该怎么做。 建议?

您需要检查每个选项值,如果该值不是空字符串,则为变量分配一个特殊值,否则只返回一个空字符串,对连接的最终 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;
}

补充说明:

  • 没有使用var/let/const声明 function 变量( urlsourcebrand等)是否有原因?

确保始终使用 let 或 const 声明变量,否则它们将在全局 scope 中可用,这是我们在 JavaScript 中尽量避免的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM