6

我有这样的代码:

$('#foo').on('click', function(e) {
   //do something
});

$('form input').on('change', function(e) {
  //do some other things
));

第一个和第二个事件实际上用相同的输入字段做同样的事情,但方式不同。问题是,当我单击#foo 元素时,表单更改元素也会触发。我需要在输入内容发生变化时触发表单更改,但在单击#foo 元素时不需要。

这就是问题所在 ))。这该怎么做?

UPD:这是 jsfiddle 上的代码:http: //jsfiddle.net/QhXyj/1/

4

4 回答 4

5

当焦点离开#input 时会触发 onChange。在您的情况下,这与单击按钮同时发生。尝试按 Tab,然后单击按钮。

为了处理这种特殊情况,一种解决方案是延迟对change事件的调用,以检查按钮是否同时被点击。在实践中 100 毫秒有效。这是代码:

$().ready(function() {

    var stopTheChangeBecauseTheButtonWasClicked = false;
    $('#button').on('click', function(e) {
        stopTheChangeBecauseTheButtonWasClicked = true;
        $('#wtf').html("I don't need to change #input in this case");
    });

    $('#input').on('change', function(e) {
        var self = this;
        setTimeout(function doTheChange() {
            if (!stopTheChangeBecauseTheButtonWasClicked) {
                $(self).val($(self).val() + ' - changed!');
            } else {
                stopTheChangeBecauseTheButtonWasClicked = false;
            }
        }, 100);
    });
});

还有小提琴 - http://jsfiddle.net/dandv/QhXyj/11/

于 2012-11-11T10:21:40.953 回答
1

在单击的元素获得焦点之前触发模糊元素上的更改事件是很自然的。如果您不想使用超时(“在输入更改后执行 X ms 操作,除非在单击按钮之间”,如 Dan 所建议的那样)-并且超时很丑-您只能执行两次这些操作。输入更改后,保存其状态并执行某些操作。如果然后 - 稍后 - 单击按钮,检索保存的状态并执行类似的操作。我想这就是你真正想要的 UI 行为,并不是所有用户都那么快。如果一个人离开输入(例如通过按Tab),然后“独立”激活按钮,您真的要执行这两个动作吗?

var inputval = null, changedval = null;

$('form input').on('change', function(e) {
    inputval = this.value;
    // do some things with it and save them to
    changedval = …
    // you might use the value property of the input itself
));

$('#foo').on('click', function(e) {
    // do something with inputval
});

$('form …').on('any other action') {
    // you might want to invalidate the cache:
    inputval = changedval;
    // so that from now on a click operates with the new value
});
于 2012-11-11T13:32:00.470 回答
0
$('form input').on('change', function(e) {
  // don't do the thing if the input is #foo
  if ( $(this).attrib('id') == 'foo' ) return;

  //do some other things
));

更新

这个怎么样:

$().ready(function() {

    $('#button').on('click', function(e) {
        $('#wtf').html("I don't need to change #input in this case");
    });

    $('#input').on('change', function(e) {
        // determine id #input is in focus
        if ( ! $(this).is(":focus") ) return;

        $(this).val($(this).val()+' - changed!');
    });  
});
于 2012-11-11T10:49:54.217 回答
0
$(function() {


          $('#button').on('click', function() {
              //use text() not html() here
              $('#wtf').text("I don't need to change #input in this case");
          }); 

          //fire on blur, that is when user types and presses tab
          $('#input').on('blur', function() {
              alert("clicked"); //this doesn't fire when you click button
              $(this).val($(this).val()+' - changed!');
          });  
      });​

这是小提琴

于 2012-11-11T11:19:20.173 回答