2

我有这个代码:

function beforemouseout() {
  if ($(this).val() == '') {
    $(this).val($(this).attr('title'));

  } 
  else {

  }
  setTimeout('beforemouseout()',3000); 
}
$(".other").click(function() {
  $(this).val('');  
  $(".other").mouseout(beforemouseout);
});
<input id="hour" type="text" class="other" autocomplete="off" value="hour" title="hour" />
<input id="hour" type="text" class="other" autocomplete="off" value="minutes" title="minutes" />

但是 Firebug 给了我一个错误: beforemouseout 没有定义。为什么?我在 jsfiddle.net 上尝试过它并没有给出错误,但结果不是我所期望的。当我点击 #hour 隐藏文本以及触发 onmouseout 等待 5 秒然后 - 时,我期望做检查

4

3 回答 3

2

像这样更改您的 setTimeout:

setTimeout(beforemouseout ,3000); 

否则,它会beforemouseout全局上下文中查找,如果您的代码不在其中(它在内部/范围为任何类型的另一个闭包),它将找不到它。我在这里猜测它在ready处理程序中,因为您在它旁边发布了 HTML,这意味着您正在获取片段。

从整体的角度来看,永远不要将字符串传递给setTimeout()或者setInterval()如果你可以避免它,它会导致许多不需要的副作用......就像这个一样。相反,像我上面那样传递一个直接引用,完全明确并且很好......让它工作:)


编辑(用于问题评论):看起来你实际上在它之后仍然与它所写的有点不同。根据我收集到的信息,您希望在将默认值恢复到<input>. 有几种方法可以做到这一点,这里是一种:

function beforemouseout() {
  if ($(this).val() == '') {
    $(this).val($(this).attr('title'));
  }
}
$(".other").click(function() {
  $(this).val('').mouseout(function() {
    setTimeout($.proxy(beforemouseout, this), 3000);
  });
});

你可以在这里试一试。​</p>

于 2010-07-25T13:03:33.660 回答
0

是的,不要将字符串作为 setTimeout 函数的参数传递,希望你能完成。顺便说一句,我认为这里不需要 setTimeout。如果每次鼠标退出时它都是空的,则您正在用“标题”填充该字段。如果你同时使用 setTimeout 和 mouseout 会增加你的函数调用指数。我想你理解我的观点。
谢谢

于 2010-07-25T13:01:01.250 回答
0

改成$(".other").mouseout(beforemouseout);这样:

$(".other").mouseout(function(){ 
  beforemouseout();
});
于 2010-07-25T13:06:30.940 回答