簡體   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