存在从函数返回值的问题

having problems returning value from functions

本文关键字:问题 返回值 函数 存在      更新时间:2024-04-09

你好,我在从AmountToDisplay()函数返回值时遇到问题,我觉得模块方法是合适的,但由于我是OOP的新手,我在设置时遇到了问题

function AmountToDisplay(){
    $emitter = $({});
    $('#amountItems').change(function(){
        var amountchosen = $("#amountItems option:selected").val();
        $emitter.trigger('amountUpdate', amountchosen);
    });
    $emitter.on('amountUpdate', function(e, val){
        if(val == 2){
            return 2;
        }else if(val == 3){
            return 3;
        }else if(val == 4){
            return 4;
        }
    })
}

我想做一些类似的事情

if(AmountToDisplay() ==2){
    ..append 2 items to body
}else if(AmountToDisplay() ==3){
    ..append 3 items to body
}

console.log(AmountToDisplay())给出未定义的

它不返回并且我使用警报方法alert(2),而是起作用。我正试图将值从选择框中取出,这样我就可以将值从事件中分离出来,这样我可以在代码的其他部分中使用该值,也可以在这个jsfiddle中使用代码中的其他部分。提前感谢您的帮助。

编辑问题是我希望能够在变更事件之外的某个地方使用金额。因此,如果用户单击3,我希望能够具有该值,这样我就可以执行与更改事件无关的另一个功能,即使该值在用户输入时发生了更改。酒吧/酒吧?

尝试通过后门。使用参数在您想要的变量中作弊。

$emitter.on('amountUpdate', function(e, val){
            console.log(arguments);
            if(val == 2){
                return 2;
            }else if(val == 3){
                return 3;
            }else if(val == 4){
                return 4;
            }
        })

您可以在参数[1]中看到所需的变量此外,在这里返回任何内容都没有任何作用。它实际上什么都没做。

您需要将其传递给事件处理程序。

因此,通过这样修改代码:

 $emitter.on('amountUpdate', function(e, val){
        val = arguments[1];
        if(val == 2){
            myEventHandlerfor2(val,e);
        }else if(val == 3){
            myEventHandlerfor3(val,e);
        }else if(val == 4){
            myEventHandlerfor4(val,e);
        }
    })

显示如何将其放入对象的编辑

function FruitBasket() {
    this.apples = 0;
    this.pears = 0;
    this.bananas = 0;
    this.iwonteatthat = 0;
}
FruitBasket.prototype.addFruit = function(which) {
    switch(which) {
        case 0 : this.apples++;break;
        case 1 : this.pears++;break;
        case 2 : this.bananas++;break;
        case 0 : this.iwonteathat++;break;
    }
}
FruitBasket.prototype.registerManipulator = function(manipulator) {
    if(!(manipulator instanceof jQuery)) {
        manipulator = $(manipulator);
    }
    manipulator.on('amountUpdate', jQuery.proxy(function(e, val){
        val = arguments[1];
        this.addFruit(val);
    },this);
}
myFruitBasket = new FruitBasket();
myFruitBasket.registerManipulator($('#formfieldstuff'));
myFruitBasket.registerManipulator(document.getElementById('OtherManipulator'));

您所拥有的返回仅退出事件的函数,而不退出AmountToDisplay函数。

  1. 事件必须在函数之外
  2. 函数只需要返回select with amountItems的值
  3. console.log或您的逻辑必须在事件中

http://jsfiddle.net/mdf083Lb/2/

function AmountToDisplay(){
    return $("#amountItems option:selected").val();
}
$("select").change(function(){
    console.log(AmountToDisplay());
});

您不需要定义事件方法或其他东西,您可以使用jquery选择器在任何您想要的地方获得选择框的选定值:

var amountToDisplay = $("#amountItems option:selected").val();