[英]JavaScript equivalent to angularjs ng-if
If I want to remove/add element on DOM
I just use ng-if
and the code under it does not compile into to DOM, can I do the same using pure js? 如果我想在DOM
上删除/添加元素,我只是使用ng-if
并且其下的代码无法编译成DOM,我可以使用纯js来做同样的事情吗? I don't want the HTML code inside my js code. 我不想在我的js代码中添加HTML代码。
Hiding it using CSS: 使用CSS隐藏它:
<div id = "infoPage" style="display: none;">
Will still insert the element to the DOM. 仍将元素插入DOM。
EDIT 编辑
The condition for showing or not is based on a flag like: 显示或不显示的条件基于如下标记:
var show = false; //or true
You can try something like this: 您可以尝试如下操作:
Object.defineProperty
. 使用Object.defineProperty
创建一个属性。 This way you can have your own setter and you can observe changes over it. 这样,您可以拥有自己的二传手,并可以观察其变化。 var CustomNGIf = function(element, callback, propertyName) { var _value = null; // Create copies of elements do that you can store/use it in future this.parent = element.parentNode; this.element = element; this.clone = null; // Create a property that is supposed to be watched Object.defineProperty(this, propertyName, { get: function() { return _value; }, set: function(value) { // If same value is passed, do nothing. if (_value === value) return; _value = !!value; this.handleChange(_value); } }); this.handleChange = function(value) { this.clone = this.element.cloneNode(true); if (_value) { var index = Array.from(this.parent.children).indexOf(this.element); // Check if element is already existing or not. // This can happen if some code breaks before deleting node. if (index >= 0) return; this.element = this.clone.cloneNode(true); this.parent.appendChild(this.element); } else { this.element.remove(); } // For any special handling callback && callback(); } } var div = document.getElementById('infoPage'); const propName = 'value'; var obj = new CustomNGIf(div, function() { console.log("change") }, propName); var count = 0; var interval = setInterval(function() { obj[propName] = count++ % 2; if (count >= 10) { window.clearInterval(interval); } }, 2000)
<div class='content'> <div id="infoPage"> test </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.