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
期望 this
是 document
(这是在您执行 document.getElementById
时设置的)。当你只是调用 $
时,没有上下文,所以 getElementById
不起作用(this
将是 window
).
试试这个:
var $ = document.getElementById.bind(document);
这将强制 this
成为 document
。
关于javascript - 试图避免重复,简化...创建全局变量并简化我的 javascript -- 纯 js 没有 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21004435/