gpt4 book ai didi

javascript - 试图避免重复,简化...创建全局变量并简化我的 javascript -- 纯 js 没有 jquery

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

function changeColor() {
var $ = document.getElementById.bind(document);
var cp = $('colorPicker');
var ct = $('col_text');
var cmess = $('colorMsg');
var cpback = $('colorPicker_back');
var rap = $('wrap');
var newColor = cp.value;

//我想让上面的内容成为全局...或者如果有另一种方式来写这个我很乐意看到。 $('col_text').style.color = newColor;

    if (newColor == "none") {
ct.innerHTML = "choose";
cpback.value = "salmon";
cmess.style.background = "#fff";
rap.style.background = "#ddd";
return this;
} else if (newColor == "yellow") {
ct.innerHTML = "yellow";
cpback.value = "salmon";
cmess.style.background = "salmon";
rap.style.background = "#ccc";

return this;
} else if (newColor == "red") {
ct.innerHTML = "red";
cpback.value = "yellow";
cmess.style.background = "yellow";
rap.style.background = "#eee";
return this;
} else if (newColor == "white") {
ct.innerHTML = "white";
cpback.value = "violet";
cmess.style.background = "violet";
rap.style.background = "#ea0";
return this;
}
}

function changeBack() {

var backgrnd = document.getElementById('colorPicker_back').value;
document.getElementById('colorMsg').style.background = backgrnd;

if (backgrnd == "none")

{
document.getElementById('col_text').style.color = "#000";
document.getElementById('col_text').innerHTML = "choose";
//document.getElementById('col_text').style.color="white";
return this;
} else if (backgrnd == "yellow")

{

document.getElementById('col_text').style.color = "red";
//document.getElementById('col_text').style.color="white";
return this;
} else {
document.getElementById('col_text').innerHTML = "choose";
return this;
}
}

//这需要简化,但我正在为如何去做而苦苦挣扎。

最佳答案

var $ = document.getElementById;

问题在于您如何保存/调用此函数。调用函数时,this 的值根据调用方式设置。

getElementById 期望 thisdocument(这是在您执行 document.getElementById 时设置的)。当你只是调用 $ 时,没有上下文,所以 getElementById 不起作用(this 将是 window ).

试试这个:

var $ = document.getElementById.bind(document);

这将强制 this 成为 document

关于javascript - 试图避免重复,简化...创建全局变量并简化我的 javascript -- 纯 js 没有 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21004435/

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