繁体   English   中英

运行一次后如何停止javascript功能?

[英]how to stop javascript function after running once?

有人可以告诉我如何运行一次此javascript函数吗? 目前,它只是一次又一次地重复,我只希望它运行一次。

我仍在学习javascript,如果不好的话,抱歉。

谢谢

<script>
$(function() {
    $(".search_prompt").hide();

    $("#text").focusin(function() {
        $(".search_prompt").show();
    }).focusout(function () {
        $(".search_prompt").hide();
    });
});
</script>
<script>
$(function() {
    $(".search_prompt").hide();

    $("#text").one('focusin', function() {
        $(".search_prompt").show();
    }).one('focusout', function () {
        $(".search_prompt").hide();
    });
});
</script>

http://api.jquery.com/one/

运行事件处理程序后,解除其绑定:

$(function() {
    $(".search_prompt").hide();
    function show_search_prompt() {
        $(".search_prompt").show();
        $("#text").unbind("focusin", show_search_prompt);
    }
    function hide_search_prompt() {
        $(".search_prompt").hide();
        $("#text").unbind("focusout", show_search_prompt);
    }
    $("#text").bind("focusin", show_search_prompt);
    $("#text").bind("focusout", hide_search_prompt);
});

工作实例

http://jsfiddle.net/bikeshedder/JqErw/


jQuery插件

如果您需要多次,可以为此编写一个JQuery插件:

$.fn.bindRunOnce = function(eventType, eventHandler) {
    this.bind(eventType, function cb() {
        $(this).unbind(eventType, cb);
        eventHandler.apply(this, arguments);
    });
};

$(function() {
    $(".search_prompt").hide();
    $("#text").bindRunOnce("focusin", function(ev) {
        $(".search_prompt").show();
    });
    $("#text").bindRunOnce("focusout", function() {
        $(".search_prompt").hide();
    });
});

现场演示

http://jsfiddle.net/bikeshedder/JqErw/1/


...或者你可以使用one通过的建议salexch

我怎么会错过这个? :-)

暂无
暂无

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

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