阻止函数执行两次

时间:2011-07-27 15:48:35

标签: jquery function

我第一次创造自己的功能$.fn.testing = function(){....};

但是我遇到了一个我无法解决的问题。下一个场景并不聪明,但它可能会发生,所以这就是为什么我要修复它以便用户不必:

$('.target').testing("message" : "Hello!");
$('#test .target').testing("message" : "Hello world!");

该功能将弹出“消息”。所以用户想要的是,对于每个.target,必须有一个带有“Hello!”的弹出框。如果此.target的id为#test,则应弹出:“Hello world!”。但问题是,现在脚本会弹出“你好!”和“Hello world!”当.target#test被触发时。

所以我在函数中想要的是函数看到函数是否已经在这个对象上被调用,如果是,它必须.unbind()之前的函数,然后继续添加函数。

我怎样才能做到这一点?希望我的解释足够清楚!

(上面的例子有点简化,所以请不要评论它的用法)

非常感谢帮助!

5 个答案:

答案 0 :(得分:2)

我将如何做到这一点:

var _myFunction = function() {
  alert($(this).data("message"));
};
插件中的

执行类似这样的操作

jQuery.fn.testing = function(msg) {
    this
        .data("message", msg)
        .unbind('click', _myFunction)
        .bind('click', _myFunction);
};

编辑:以下是jsfiddle

中的示例

答案 1 :(得分:1)

你可以这样做:

$('.target#test').testing("message" : "Hello world!");
$('.target:not(#test)').testing("message" : "Hello!");
编辑 - 你的意思是这样吗?

$('.target').testing(function(e){
   if (this.id === 'event'){
        alert('hello world');
   }else{
        alert('hello');
   }
});

答案 2 :(得分:0)

试试这个

var $this. msg;
$('.target').each(function(){
  $this = $(this);

  if((#this.attr("id) != "#test") || ($this.find("#test").length == 0))//here check for all the possible ids you want){
      msg = "message" : "Hello world!";  
  }
  else{
      msg = "message" : "Hello!";
  }
  $this.testing(msg);
});

答案 3 :(得分:0)

据我了解:例如,你有一个弹出目标元素的目标元素,现在弹出窗口是一个目标子,或者你可能已经实现了。我的观点是每当调用该函数时,它将检查弹出是否插入到DOM中。如果它是第一个,它将删除该弹出窗口,然后插入带有新消息的新弹出窗口。

我的意思是... ...

    function() {
        //if a pop is present
        $('.popup').remove();

        var msg = $(this).attr('title'); //for example
        var popup = "html containin msg...";
        $(this).append(popup);
    } 

答案 4 :(得分:0)

不知道这是否是正确的做法,但我自己也把它弄清楚了。这很简单,只需在您自己的函数开头添加$(this).unbind()即可。它将删除所有以前添加的功能,并仍然继续添加当前功能。我曾经尝试过,但是使用了一个额外的选择器:$(this).unbind(".testing"),由于某种原因无效,但现在我已经开始工作了。

感谢您的回答并得到您的帮助!真的很感激!

相关问题