JS中的initial
值在CSS中是否等效。当您有一个函数要使用if语句以某种方式运行时,但是,在else
部分中,您希望这些值只是在if
代码返回true之前的值。我一直都将原始值重写为else
的一部分,但这似乎是执行效率低下的方法,例如:
var a = something, b = something_else;
if (a) {
run a function which changes lots of values;
} else {
re-type the values to what they were before the function ran;
}
下面是我要尝试的更具体的版本。我有一个forEach方法,可以更改一些字符串值。如果我要进行设置,以便在
else
上忽略初始if
中的所有代码,我知道我可以通过将代码复制并粘贴到其他函数名下并将第二个slice
值设置为来做到这一点。 300,这是原始字符串的长度,但是这似乎是一种非常冗长的处理方式?必须有一种设置
else
代码的方法,以便它删除/删除原始的myresize()函数,以便所有原始值都成立吗?var content = document.querySelectorAll(".generic-content p");
function textSlice() {
if (window.innerWidth < 500) {
function myresize() {
content.forEach(function(index) {
var x2, x3, x4;
x2 = index.textContent;
x3 = x2.slice(0, 100) + "[...]";
index.textContent = x3;
});
myresize();
}
} else {
// remove the myresize(); function or somehow kill it
}
}
addEventListener("resize", textSlice, false);
最佳答案
JavaScript中没有内置的功能可以还原元素的初始状态。但是,构建这样的功能相对容易。在开始之前,请将状态保存到全局对象,然后可以使用该对象随时恢复初始状态。
试试下面的代码。请注意,forEach
方法的第一个参数是元素本身,而不是索引。因此,将其命名为index
是不正确的。我已将其更改为item
。
var content = document.querySelectorAll(".generic-content p");
//Save the initial state.
var initial = [];
(function() {
content.forEach(function(item) {
initial.push(item.textContent);
});
})();
function textSlice() {
if (window.innerWidth < 500) {
content.forEach(function(item) {
var x2, x3, x4;
x2 = item.textContent;
x3 = x2.slice(0, 100) + "[...]";
item.textContent = x3;
});
} else {
//Restore the initial state.
content.forEach(function(item, index) {
item.textContent = initial[index];
});
}
}
addEventListener("resize", textSlice, false);
<div class="generic-content">
<h4>Window Resize Demo</h4>
<p>first paragraph</p>
<p>second paragraph</p>
<p>third paragraph</p>
</div>