简体   繁体   English

从同一函数返回在函数内的事件处理程序中创建的值

[英]Return a value created in an event handler inside a function from the same function

I have an input box and a go button.我有一个输入框和一个 go 按钮。 When the user clicks the go button I want to compare the inserted value with another value.当用户单击 go 按钮时,我想将插入的值与另一个值进行比较。 I am trying to acquire the input value inside a function like so我试图在这样的函数中获取输入值

function getInput(){
        var entry ='';
        $('button.go').on('click',function(){
            var entry = $(this).siblings('.input').val();
            //return entry
        })
        return entry


}

Basically I want to return the var entry that has an input value, so I could compare the values later in the code基本上我想返回具有输入值的 var 条目,因此我可以稍后在代码中比较这些值

var input = getInput() // this should have input value
is input > othervalue

I call getInput inside document.ready()我在 document.ready() 中调用 getInput

You are doing everything right .你做的一切都是正确的。 There are some scope related issues that is not helping you to get the expected result .有一些范围相关的问题不能帮助您获得预期的结果。 My suggestion would be to define othervalue variable as global and check it inside the function like this我的建议是将othervalue变量定义为全局变量并像这样在函数内部检查它

function getInput(){       
    $('button.go').on('click',function(){
       var entry = $(this).siblings('.input').val();     
        if(entry>othervalue) //your code     
    });     
}

I am not sure why you are binding dynamic click event inside a function .我不确定您为什么要在函数内绑定动态click事件。 If there is nothing else you need to do here except this part, then wrap this piece of code inside document.ready .如果除了这部分你不需要做任何其他事情,那么把这段代码包装在document.ready

I would suggest to declare your var entry ='';我建议声明你的var entry =''; globally and assign it before comparing.全局并在比较之前分配它。

var entry="";
$('button.go').on('click',function(){
     entry = $(this).siblings('.input').val();
});
//do the comparing..

You should do the comparing, after delegating the click function, inside the function.您应该在委托点击功能后,在功能内部进行比较。

var entry = "";
$('button.go').on('click', function(){
     var entry = $(this).prev('.input').val();
     if (entry < x)
         // Do something
});

It remains unclear to me what you want to accomplish.我不清楚你想完成什么。

I made some code that might be somewhere near what you want.我制作了一些可能接近您想要的代码。

 jQuery().ready(function() { var startValue = $('input[name="the_input"]').val(); $('form').submit(function() { var currentValue = $('input[name="the_input"]').val(); $('body').append('<br />' + startValue + ' - ' + currentValue + ' = ' + (startValue - currentValue)); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form action="#" method="post"> <input type="text" value="10" name="the_input" /><br /> <input type="submit" value="go!" /> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM