簡體   English   中英

輸入值不隨用戶輸入而變化

[英]Input value not changing with user input

我正在通過Odin Project進行嘗試,嘗試使用jQuery創建“ etch-a-sketch”類型的網站。 這個想法是讓div的內部帶有網格,當鼠標懸停在網格上時,網格正方形會改變顏色。 用戶還應該能夠輸入他們想要多少個網格正方形,因此,如果在表單中放置16個,則將獲得16x16的網格。

我將初始值設置為16。當我輸入一個不同的數字並按“ go”時,該值將更改回16,並且網格保持不變。 我要去哪里錯了?

謝謝!

相關代碼如下:

HTML:

<form>
    <label>Enter the width in pixels:</label>
    <input id="formbox" type="text" value="16">
    <input id="setWidth" class="buttons" type="submit" value="Go!">
    <button id="reset" class="buttons" type="reset">Reset</button>
</form>

JS:

$('#setWidth').click(function () {
    $('.box').css("background-color", "#fff");
    $('.box').remove();

    var $divWidth = $('#formbox').val();

    for (var i = 0; i < $divWidth; i++) {
        $('#canvas').append('<div class="divHolder"></div>');
        $('.divHolder').css("height", Math.floor(500 / $divWidth));
    }

    for(var i = 0; i < $divWidth; i++) {
        $('.divHolder').append('<div class="box"></div>');
        $('.box').css("width", Math.floor(500 / $divWidth));
        $('.box').css("height", Math.floor(500 / $divWidth));
    }
});

您應該能夠在事件上使用preventDefault()函數。

此功能停止默認行為(在這種情況下,默認情況下應刷新頁面是該行為)。

$('#setWidth').click(function (e) {
    e.preventDefault();
    $('.box').css("background-color", "#fff");
    $('.box').remove();

    var $divWidth = $('#formbox').val();

    for (var i = 0; i < $divWidth; i++) {
        $('#canvas').append('<div class="divHolder"></div>');
        $('.divHolder').css("height", Math.floor(500 / $divWidth));
    }

    for(var i = 0; i < $divWidth; i++) {
        $('.divHolder').append('<div class="box"></div>');
        $('.box').css("width", Math.floor(500 / $divWidth));
        $('.box').css("height", Math.floor(500 / $divWidth));
    }
});

暫無
暫無

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

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