【问题标题】:Call a function inside another function and then stop it javascript在另一个函数中调用一个函数,然后停止它 javascript
【发布时间】:2015-04-30 09:40:00
【问题描述】:

我有一个文件输入,在其上调用了两个函数f()colorit()。如果在f() 中不满足指定条件,我想停止函数colorit()。但是,一旦选择了文件,两个函数就会启动。

<body>
    <div class="dClass">
        <input type="file" class="iClass" />
    </div>

    <script> 
        function f(){
            if () { 
                // if image selected does not meet requirements
                // how to stop colorit(); function here ??
                return false;
            }
            else {
               alert("done");
            }
        }

        $('.iClass').change(function() { 
           f(); // calling function f
        });

        $(function() {
           $('.dClass').colorit();
           //note: colorit() function also comes to action as soon as a file is selected through .iClass
        });
    </script>
</body>

【问题讨论】:

  • color 是一个改变div背景的功能,我想要的是如果图片不符合条件不实现为背景
  • ...你的 colorit 函数运行onload...是循环还是什么? 0_o

标签: javascript jquery html css function


【解决方案1】:

您可以通过在其中使用 this 来强制停止函数执行,而不是 recomanded ,但这是一种方式

throw new Error('This is not an error. This is just to abort javascript');

【讨论】:

  • 这是什么新东西??
  • throw 语句抛出用户定义的异常。当前函数的执行将停止(throw 之后的语句不会被执行),控制权将传递给调用堆栈中的第一个 catch 块。如果调用函数之间不存在 catch 块,则程序将终止。
  • 你能让我们成为 JsFiddle 吗?
  • 第一个小提琴,link 。在这个中,无论是否满足 f() 的条件 colorit() 都会改变背景图像。第二小提琴link。在这一个 f() 验证 if 条件但颜色它不起作用。
  • 在 jsFiddle 中你使用 jquery 但没有选择库,它是否有效,或者你只是再次粘贴代码?有一个问题,colorit() 是一个插件吗?或者你做的东西?你的意图是什么?上传一张图片,如果它通过某些条件,然后将其设置为背景?
【解决方案2】:

删除 -

$(function() {
   $('.dClass').colorit();
}

如果您只希望colorit()f() 成功的情况下工作。

定义f()like -

function f(obj){
    if () { // if image selected does not meet requirements
       // how to stop colorit(); function here ??
       return false;
    }
    else {
       obj.colorit();
       alert("done");
    }
}

这样您就可以在 sicceeds 时使用该对象启动 colorit

并致电f() 喜欢 -

$('.iClass').change(function() { 
   f($('.dClass')); // calling function f
});

另一种方法是 -

function f(obj){
    if () { // if image selected does not meet requirements
       // how to stop colorit(); function here ??
       return false;
    }
    else {
       obj.data('fdone', 1);
       alert("done");
    }
}

还有

$('.iClass').change(function() { 
   f($('.dClass')); // calling function f
   if($(this).data('fdone') == 1) {
      $('.dClass').colorit();
   }
});

还有——

<input type="file" class="iClass" data-fdone='0' />

【讨论】:

  • 是的,看来值得一试
  • 你收到警报了吗?
  • Colorit() 是一个来自 jquery 插件的巨大函数,这会影响它的功能吗??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 2014-07-14
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多