【问题标题】:Prevent paragraph from adding new line (JAVASCRIPT, HTML)防止段落添加新行(JAVASCRIPT、HTML)
【发布时间】:2022-11-04 07:22:54
【问题描述】:

我正在编写一个程序,它将通过一系列信息显示国家和子县。我决定包含一个部分,而不是在文本区域中显示,我只是希望它通过段落输出显示。

但是,如果用户再次单击该按钮,它将继续复制和粘贴输出。我想防止这种情况,以防用户执行此操作 [多次按下按钮后的当前结果][1] https://i.stack.imgur.com/enZVW.png

如果再次单击该按钮,它将多次显示结果。

[我希望它在多次按下按钮后的样子][2] https://i.stack.imgur.com/dXqYE.png

HTML

    <input type="input" id="city"><br><br>
    <button id="button2">   <!-- Giving button an ID to be called out in our init function and add an eventlistener -->
    Show country/subcountry</button><br><br><br>
        
   <!--  <textarea readonly id="countryOut" style="overflow-y:scroll; 
    resize: none; margin-left: 2.7em; " ></textarea><br><br>  -->

   <p id = "countryOut"></p><br><br>

JAVASCRIPT

    // display += `${sub}, ${co}\n \n`; // display subcountry, and country with new lines included for spacing
    p2.innerHTML += `${sub}, ${co}\n \n`;
    }
    
    }
    
    }

function init() {
    var button = document.getElementById("button1"); // When country is entered, cities will display 

    button.addEventListener("click", getCountrySub); // when click event/action is performed, the function of getCountry will execute

    var button2 = document.getElementById("button2"); // when city is entered, the region, country, sub country, etc. will display

    button2.addEventListener("click", getCities); // when click event/action is performed, the function of getCities will execute
   
}```

【问题讨论】:

    标签: javascript java html output


    【解决方案1】:

    += 标志正在制作重复的文本。
    将此修复为 = 将按您的意图工作。

    // AS-IS
    p2.innerHTML += `${sub}, ${co}`
    
    // TO-BE
    p2.innerHTML = `${sub}, ${co}`
    

    【讨论】:

      【解决方案2】:

      感觉代码不完整,假设这是一个遍历两个列表的循环

      p2.innerHTML += `${sub}, ${co}`
      

      然后我认为你在开始输出之前缺少清理,所以在循环开始之前试试这个:

      p2.innerHTML = ""; // trick is here, when button is clicked clear old results, then show new information
      for (const co of countries) { // Please fix to your variable names
        for (const sub of co.sub) {
          p2.innerHTML += `${sub}, ${co}`;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-15
        • 2015-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-28
        相关资源
        最近更新 更多