簡體   English   中英

如何讓我的JQuery作用於我的按鈕而不是輸入元素

[英]How to get my JQuery to act on my button rather than the input element

我正在嘗試使用以下按鈕元素將輸入數字增加1,同時用戶按住鼠標左鍵按下按鈕。 使用下面的代碼,它幾乎正在執行所述行為,除了它只在我單擊html輸入元素中內置的箭頭時才這樣做。 我希望當我點擊我的按鈕元素時發生這種情況,我不明白為什么沒有發生這種情況。

HTML

<input type="number" class = "margin" value="0">
<button id="clicker" type="button" class ="away">Add one</button>

JQuery--

$(document).ready(function () {

    function decrement(field) {
        field.val(parseInt(field.val(), 10) - 1);
    }
    var timeout, clicker = $('#clicker');

    $("#clicker").mousedown(function () {
        timeout = setInterval(function () {
            // Do something continuously 
            decrement($(this).siblings('.margin'));
        }, 500);

        return false;
    });

    $(document).mouseup(function () {
        clearInterval(timeout);
        return false;
    });

});

HTML

<html>
<input type="number" class = "margin" value="0">
<button id="clicker" type="button" class ="away">Add one</button>

你應該使用click()而不是mousedown()mouseup() ,你也沒有在setInterval()得到$(this) setInterval()試試這個,

$(document).ready(function () {
    function decrement(field) {
        field.val(parseInt(field.val(), 10) - 1);
    }
    var timeout, clicker = $('#clicker');
    $("#clicker").click(function (e) {// use click in place of mousedown
       $that=$(this);// take a copy of ($this);
       timeout = setInterval(function () {
            // Do something continuously 
            decrement($that.siblings('.margin'));// use $that in place of $(this)
       }, 1000);
       return false;
    });
    $(document).click(function (e) {// use click in place of mouseup
        clearInterval(timeout);
        return false;
    });
});

工作演示

問題是你的背景下this 在定義間隔之前,需要在mousedown事件中為按鈕創建句柄:

var timeout;

$("#theButton").on('mousedown', function () {
    var theButton = 'this'; // handle on the button
    timeout = setInterval(function () {
        var value = +$(theButton).prevAll("#field").val();
        value++;
        $(theButton).prevAll("#field").val(value);
    }, 500);
});

$("#theButton").on('mouseup', function () {
    clearInterval(timeout);
});

這是一個小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM