javascript只执行一次

时间:2014-05-19 09:41:21

标签: javascript

我有以下功能,每次点击它们都会让我的元素反弹。我怎么能实现我只能在每个元素上单击一次,如果我再次点击以获得警报("已经点击了我")?

// Bounce On Click
function bounceOnClick(view) {

    // If the view is a normal view (not a scrollview)
    if (view instanceof View) {

        // Listen to a click event
        view.on("click", function (event) {

            // Stop sending the click event to underlying views after this
            event.stopPropagation()

            // "Wind up" the spring
            view.scale = 0.7

            // And scale back to full size with a spring curve
            view.animate({
                properties: {
                    scale: 1.0
                },
                curve: "spring(1000,15,500)"
            })
        })
    }
}
// Loop through all the exported views
for (var layerGroupName in PSD) {
    bounceOnClick(PSD[layerGroupName]);
}

3 个答案:

答案 0 :(得分:2)

在JavaScript中,所有对象都是动态的,因此您可以添加要查看的属性:

view.on("click", function (event) {
    if (this.clicked) {
        alert("already clicked!");
    } else {
        // your code
        this.clicked = true;
    }
});

答案 1 :(得分:0)

这样的事情应该这样做:

function bounceOnClick(view) {
    if (view instanceof View) {

        // Listen to a click event, and run this handler only once.
        view.one("click", function (event) {
            event.stopPropagation();
            view.scale = 0.7;
            view.animate({
                properties: {
                    scale: 1.0
                },
                curve: "spring(1000,15,500)"
            })

            // New event handler: notify the user the element was clicked before.
            view.on("click", function (event) {
                event.stopPropagation();
                alert("already clicked me!");
            })
        })
    }
}

这使用jQuery的.one() event handler只运行一次第一个函数,然后使用"already clicked me!"警报分配一个新的事件处理程序。

答案 2 :(得分:0)

您可以使用jquery .one()

Jquery .one(): - 将处理程序附加到元素的事件。每个事件类型的每个元素最多执行一次处理程序。

试试这个:

 view.one("click", function (event) {
 // Your Code
 });