试图使用array.push();使用换行但使用纯文本,而不是HTML 标签

问题描述 投票:0回答:2

最近我一直试图抓取HTML表单输入数据,添加一个前缀,然后将其写回<div>例如:

HTML:

<h1>Please enter Details</h1><hr>

GUID <a href="https://www.guidgenerator.com/online-guid-generator.aspx">(Generator)</a>:<div id="guidInput" style="display:inline;">
    <!-- Changed to an onkeyup="" method. Works the same but with less code. -->
    <input onkeyup="gen()" id="guidText" style="height: 16px;"></input>
</div>

ID:<div id="idInput" style="display:inline;">
    <!-- Changed to an onkeyup="" method. Works the same but with less code. -->
    <input type="number" type="number" onkeyup="gen()" id="idText" style="height: 16px;"></input>
</div>


<div id="command" class="command"></div>

JS:

$(document).ready(function(){
    var command = ""; /*Here for future developement*/
    command += "";  /*Here for future developement*/
    document.getElementById('command').innerHTML = command; 
});


function gen() {

    var id = $('#idText').val(); 
    var guid = $('#guidText').val(); 
    var command = "";  /*Here for future developement*/
    var tags = []; 

    tags.push("GUID "+guid);
    tags.push("ID "+id);

    command += tags.join("<br>"); 
    command += ""; /*Here for future developement*/
    document.getElementById('command').innerHTML = command;
}

这就是我想要的:https://imgur.com/a/QrwD7但我希望用户将输出下载为文件。为此,我实现了FileSaver.js,并将此代码添加到我的文件中:

HTML(位于<div id="command" class="command"></div>上方):

<button onclick="saver()">Save</button>

JS:

function saver() {

  var text = document.getElementById("command").innerHTML;
  var newText = text.replace(/(<([^>]+)>)/ig,"");
  var filename = ("File")
  var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
  saveAs(blob, filename+".txt");
}

它抓住包含输出的<div>的内容,并触发下载File.txt。此文件的内容如下所示(来自上面的imgur.com链接。):

GUID qwertyuiop<br>ID 12345

这就是我遇到问题的地方。我需要文件看起来像这样:

GUID qwertyuiop
ID 12345

每个部分后都有换行符。 <br>用于在网站上显示它,但我需要一些方法来确保它在下载文件中的单独行上,并且文件中没有HTML标记。

javascript jquery html
2个回答
0
投票
var newText = text.replace(`<br>`, `\n`).replace(/(<([^>]+)>)/ig,"");

要么

function gen(delimiter) {

    // ... //

    command += tags.join(delimiter); 
    return command;
}

function saver() {

  // ... //
  var newText = gen(`\n`);
  // ... //
}

-1
投票

您的代码违反了SRP:单一责任原则。

你试图同时做两件事。

HTML中的前缀和格式是两个不同的问题,它们应该分开。

在那之后,答案将变得明显。

© www.soinside.com 2019 - 2024. All rights reserved.