0

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

我还在学习javascript,如果不是很好,很抱歉。

谢谢

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

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

2 回答 2

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

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

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

于 2013-02-03T13:48:55.930 回答
0

运行后取消绑定事件处理程序:

$(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.

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

于 2013-02-03T13:49:37.200 回答