简体   繁体   English

在JavaScript中的div之前添加换行符

[英]Adding a line break before a div in javascript

I have a JavaScript function that runs when an html button is clicked. 我有一个JavaScript函数,可在单击html按钮时运行。 If an error occurs in the function i display an error which is just an html div that i add text to dynamically and is usually hidden until the error occurs. 如果在函数中发生错误,我会显示一个错误,它只是一个html div,我会动态添加文本,并且通常是隐藏的,直到发生错误为止。 I would like to dynamically add a line break (br) before the error display (before the div) at the same time. 我想在错误显示之前(在div之前)动态地添加一个换行符(br)。

My issue is that, if the user keeps clicking the button and an error keeps occurring, the page fills up with line breaks and the rest of the page moves down. 我的问题是,如果用户继续单击该按钮并且不断发生错误,则该页面将充满换行符,而页面的其余部分将向下移动。 So the breaks are compounding and never going away. 因此,休息越来越复杂,而且永远不会消失。 Here is the JavaScript which dynamically adds the error text to the div and a line break before it. 这是JavaScript,可将错误文本动态添加到div,并在其之前添加换行符。

$('#sku-upc-error').html(jqXHR.responseText).before("<br />");

Here is the html that displays the error. 这是显示错误的html。

<div class="error-display" id="sku-upc-error"></div>

I can hide or remove the div dynamically, when the error doesn't occur but the line breaks are still there. 当没有发生错误但换行符仍然存在时,我可以动态地隐藏或删除div。 like this for example: 例如:

$("#sku-upc-error").hide();

Is there a way to remove the line breaks too? 是否也有办法消除换行符? Or a better way to add the breaks before the error div so that they don't stay on the page and compound if errors keep occurring? 还是一种在错误div之前添加中断的更好的方法,以使它们不会停留在页面上并且如果错误不断发生又会加重?

You can, here is a neat little trick. 您可以,这是一个巧妙的小技巧。

When you add the line breaks, add a class to them like so... 添加换行符时,请像这样向其添加类。

$('#sku-upc-error').html(jqXHR.responseText).before("<br class='break' />");

Then when you run the code to hide the error message, include this code directly after it to remove the line breaks. 然后,当您运行代码以隐藏错误消息时,请在代码后直接添加该代码以删除换行符。

$(".break").remove();

Give that a try and let me know how you get on. 试试看,让我知道你过得如何。 You can also use .hide() if you wanted but this removes them all from the DOM properly rather than hiding them but keeping them within the markup. 如果需要,还可以使用.hide() ,但这可以将它们全部从DOM中正确删除,而不是隐藏它们,而是将它们保留在标记中。

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

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