gpt4 book ai didi

javascript - 通过删除函数重置 if/else 语句的 Else 部分中的修改值

转载 作者:行者123 更新时间:2023-11-30 20:50:09 25 4
gpt4 key购买 nike

在 JS 中是否有等效于 CSS 中的 initial 值。当您有一个函数,您希望通过 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 中的所有代码,我知道我可以通过在不同的函数下复制和粘贴代码来做到这一点name 并将第二个 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>

关于javascript - 通过删除函数重置 if/else 语句的 Else 部分中的修改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48268100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com