输入选择器未被重置

时间:2015-02-21 00:47:17

标签: javascript jquery html

我的HTML看起来像:

<input type="number">
<br>
<input type="number">
<br>
<input type="number">
<br>
<button>+</button>

我的JS

$('input').on('click', function () {
    var input = $(this);
    $('button').on('click', function () {
        var newVal = parseInt(input.val()) + 1;
        input.val(newVal);
    });
});

每次我切换输入以使用加号按钮编辑值时,之前点击的输入也会被更改。

我该如何正确地做到这一点,以便只有&#34;这个&#34;选定的输入是否被编辑?

JSFiddle:http://jsfiddle.net/qh8sqd09/

2 个答案:

答案 0 :(得分:0)

将最后点击的输入保存在变量中。单击加号按钮时,将添加最后一次单击输入的值。

var last_clicked;

$('input').on('click', function () {
    last_clicked = $(this);
});

$('button').on('click', function () {
    var newVal = parseInt(last_clicked.val()) + 1;
    last_clicked.val(newVal);
});

Fiddle

答案 1 :(得分:0)

我认为,实现这一目标的最简单方法是将类名(或自定义data-*属性)分配给最后点击的元素,然后点击<button>查找具有该类名(或自定义属性)的元素作为标识符。例如:

&#13;
&#13;
// select all the <input> elements,
// binding an anonymous function to handle the focus event:
$('input').on('focus', function() {
  // selecting the <input> elements with the 'lastActive'
  // class-name, removing that class:
  $('input.lastActive').removeClass('lastActive');
  // adding the 'lastActive' class-name to the focused element:
  $(this).addClass('lastActive');
});

// selecting the <button> element, and binding an event-handler
// for the click event:
$('button').on('click', function(e) {
  // preventing the default action of a <button> (usually,
  // when wrapped in a <form> the <button> submits that <form>:
  e.preventDefault();

  // finding the <input> element with the 'lastActive' class-name,
  // updating its value:
  $('input.lastActive').val(function(i, v) {
    // first argument (here: 'i'), the index of the current element
    // in the jQuery collection,
    // second argument (here: 'v'), the current value held by the
    // <input> element

    // if v is a falsey-value, we return 1 otherwise
    // we parse the attribute-value with parseFloat (to
    // ensure it's a number) and add 1 to that number:
    return !v ? 1 : parseFloat(v) + 1;
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" />
<br />
<input type="number" />
<br />
<input type="number" />
<br />
<button>+</button>
&#13;
&#13;
&#13;

参考文献: