试图通过模块模式在DOM元素上实现change()事件

Trying to implement a change() event on a DOM Element through the module pattern

本文关键字:实现 change 事件 元素 DOM 模块 模式      更新时间:2023-09-26

我有一个复选框,当用户单击它时,我希望它更改私有变量output。然后我想将对象的属性更新为输出。在下面的代码中,我无法使更改事件工作,我相信这是因为我不知道如何通过Module模式与DOM元素交互。所以如果你能帮上忙那就太好了。

另外一个让我担心的问题是,我希望在用户单击时更新apple对象中的价格变量。每次用户单击复选框时,价格都会更改为一个随机数。我总是在更新更改事件之外的对象时遇到问题,就像您在我的代码中看到的那样。apple.price在变更事件之外。如果你能告诉我,我也将不胜感激。

var CreatItems = function(name, price, pic){
    this.name = name;
    this.price = price;
    this.pic = pic;
}
CreatItems.prototype.listOut = function(){
    console.log(this.name + this.price + this.pic)
}
var changingPrice = (function(){
    // testMethod : function(){
    //  return 1.77
    // }
    var output;
    var testMethod = function(){
        return output
    }
    var clickedWithOnes = function(){
        $("#withones").change(function(){
            if(this.checked){
                // output = "checked";
                console.log("Checked")
            }else{
                // output = "unchecked";
                console.log("unchecked")
            }
        })
    }
    return{
        testMethod : testMethod,
        clickedWithOnes : clickedWithOnes
    }
})()
changingPrice.clickedWithOnes()
var price = changingPrice.testMethod()
// console.log(price)
var apple = new CreatItems("apple", price, "will be red div")
console.log(apple.price)

我得到了"未定义"的安慰

嗨,我为您创建了列表,请查看:链接到这里新的

你还有下一个问题,你的工作几乎很好,你只有一个问题:当你返回你的output值时,它会像一个值一样返回,但如果你想保持output和新的apple变量之间的连接,你应该像一个对象一样返回它。