Jquery function return value

后端 未结 2 618
忘掉有多难
忘掉有多难 2021-01-31 08:56

I\'ve created a function to iterate through a UL/LI. This works perfectly, my problem is returning the value to another variable. Is this even possible? What\'s the best method

相关标签:
2条回答
  • 2021-01-31 09:37

    The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

    function getMachine(color, qty) {
        var returnValue = null;
        $("#getMachine li").each(function() {
            var thisArray = $(this).text().split("~");
            if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
                returnValue = thisArray[3];
                return false; // this breaks out of the each
            }
        });
        return returnValue;
    }
    
    var retval = getMachine(color, qty);
    
    0 讨论(0)
  • 2021-01-31 09:49

    I'm not entirely sure of the general purpose of the function, but you could always do this:

    function getMachine(color, qty) {
        var retval;
        $("#getMachine li").each(function() {
            var thisArray = $(this).text().split("~");
            if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
                retval = thisArray[3];
                return false;
            }
        });
        return retval;
    }
    
    var retval = getMachine(color, qty);
    
    0 讨论(0)
提交回复
热议问题