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

标签 javascript function oop object

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/

相关文章:

javascript - 选择字段中的空白选项

javascript - chrome 和 safari 中的 contenteditable 用内联样式替换 css 类和规则

python - 涉及列表的格式问题

PHP 将默认参数传递给函数

python - 为什么 Python 不完全面向对象?

matlab - 为什么定义 MATLAB containers.Map 子类方法时输出为 "too many output arguments"?

javascript - 为什么这个js数组函数不起作用?

javascript - 是否可以在javascript中获取Mongodb记录的创建日期?

函数中的python语法错误

php - 遍历 PHP 对象