简体   繁体   English

使用JS更改div中的内容而不破坏其内容

[英]Changing content in a div with JS without destroying its content

I am using an application where on change in the select box value my javascript function would be called. 我正在使用一个应用程序,该应用程序会在选择框值发生变化时调用我的javascript函数。 In the function I have an if/else statement. 在函数中,我有一个if / else语句。 If the condition validates, it displays me a graph in my div , else it displays text in the same div . 如果条件有效,它将在我的div显示一个图形,否则将在同一div显示文本。

var arrayDataSource = [];
//for example this array has the following [[1,0.2],[2,0],[3,1]
$.each(test, function(index, value) 
{
    //code to load data to that array
});
)
if(arrayDataSource.length > 0) {
    //draw graph
} else {
    document.getElementById('mydiv').innerHTML = "some text";
}

When I try to run the else condition my content gets overwritten as I am using an innerHTML to display text. 当我尝试运行else条件时,由于使用innerHTML显示文本,我的内容被覆盖。

Do I have any other options to display text with javascript without using innerHTML ? 我还有其他选择可以使用javascript显示文本而不使用innerHTML吗? I have also seen some DOM functions and other relevant posts but nothing worked for me. 我也看到了一些DOM函数和其他相关文章,但对我没有任何帮助。 My div properties should remain as they are even after the else condition. 即使在else条件之后,我的div属性也应保持不变。

Use insertAdjacentHTML instead of innerHTML as it does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. 使用insertAdjacentHTML而不是innerHTML,因为它不会重新解析正在使用该元素的元素,因此不会破坏该元素内部的现有元素。

document.getElementById('overAllContainer').insertAdjacentHTML('beforeend', 'some text');

A better way to do it would be to append a new element with an attribute such as a class or an id to your overAllContainer in order to easily remove it when your selection changes. 更好的方法是将一个具有类或id之类的属性的新元素添加到overAllContainer中,以便在选择更改时轻松将其删除。 You can do it via 您可以通过

document.getElementById('overAllContainer').insertAdjacentHTML('beforeend', '<p class="message">some text</p>');

Or via 或通过

var message = document.createElement('p');
message.setAttribute('class', 'message');
message.innerText = 'some text';
document.getElementById('overAllContainer').appendChild(message);

And then when you want to remove the message based on the selection changing, 然后,当您要根据选择的更改删除消息时,

document.querySelector('#overAllContainer .message').remove();

Changing content in a div with JS without destroying its content you can simply use +=; 使用JS在div中更改内容而不破坏其内容,您可以简单地使用+=; instead of = only. 而不是=仅。

The code will be document.getElementById('overAllContainer').innerHTML += "some text"; 代码将为document.getElementById('overAllContainer').innerHTML += "some text";

Use document.createTextNode : 使用document.createTextNode

var text = document.createTextNode("some text");
document.getElementById('mydiv').appendChild(text);

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

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