将数据发送到绑定函数。结构“click:function(){...}”

时间:2010-11-09 14:20:57

标签: jquery events bind

我可以发送这样的数据(数据不同)?

$("div.test").bind("click", {foo: "bar1"}, function(event) { ... })
$("div.test").bind("mouseenter", {foo: "bar2"}, function(event) { ... })
$("div.test").bind("mouseleave", {foo: "bar3"}, function(event) { ... })

但有了这种结构:

$("div.test").bind({
  click: function(){ ... },
  mouseenter: function(){ ... },
  mouseleave: function(){ ... }
});

并且也可以发送相同的信息,“但不是在用数据声明变量之前:

不是这个:

var data = "test";
$("div.test").bind({
  click: function(){ 
   // use data
  },
  mouseenter:{ 
   // use data
  },
  mouseleave: { 
   // use data
  }
});

感谢

2 个答案:

答案 0 :(得分:1)

我不确定为什么这很重要,但如果你不想让它再次运行选择器,你可以做两件事:
1)在绑定之前保存对象:

var $mytest = $("div.test");
$mytest.bind("click", {foo: "bar1"}, function(event) { ... });
$mytest.bind("mouseenter", {foo: "bar2"}, function(event) { ... });
$mytest.bind("mouseleave", {foo: "bar3"}, function(event) { ... });

2)你可以链接它们:

$("div.test").bind("click", {foo: "bar1"}, function(event) { ... })
    .bind("mouseenter", {foo: "bar2"}, function(event) { ... })
    .bind("mouseleave", {foo: "bar3"}, function(event) { ... });

您还有其他原因想要这样做吗?

修改
要明确回答这个问题,如果不使用jQuery“map”对象格式将其声明为外部,则无法传递数据。除非您手动触发事件,否则我认为这不是您想要做的事情。

答案 1 :(得分:0)

好吧,不是我想要的,但它对我有用:

HTML

<button id="test">test</button>
<div id="data-event"></div>

JS

var fn = function(event) {

    $("#data-event").append("<div>" + event.data[event.type].xx + "</div>");

};

$("#test").bind(
    {
      click:  fn,
      mouseover: fn
    },
    {click: { xx: "click-text" }, mouseover: { xx: "mouseover-text" } });

example