簡體   English   中英

從輸入數據屬性將變量插入 HTML

[英]Insert variable into the HTML from the input data attribute

我正在嘗試將價格插入 html 元素中,該元素是從輸入“數據”值中獲取的。

第一個 function 工作正常,但第二個總是給 0。

$(document).ready(function() {

    if ($('input[name="bedrooms"]').is(':checked')) {
        var bedroomPrice = $('input[name="bedrooms"]:checked').data('price');
    } else {
        var bedroomPrice = 0;
    }

    $('input').on('change', function() {
        $('#total').html(bedroomPrice);
    });

});

你能告訴我我做錯了什么嗎?

僅在頁面加載時才使用為變量賦值。 實際上,您需要在更改輸入時更新變量的值。 這是更新的JS代碼:

$(document).ready(function() {
    var bedroomPrice = 0;
    $('input').on('change', function() {
        if ($('input[name="bedrooms"]').is(':checked')) {
            bedroomPrice = $('input[name="bedrooms"]:checked').data('price');
        } else {
            bedroomPrice = 0;
        }
            $('#total').html(bedroomPrice);
    });
});

現在它會在輸入發生變化時檢查卧室價格,這是最新值。

此外,如果您有多個卧室選擇,並且您只想顯示選中復選框的價格(考慮到用戶當時只能選中任何 1 個復選框)。 使用this (這是當前元素對象)而不是input[name="bedrooms"] 所以 JS 代碼會變成這樣:

$(document).ready(function() {
    var bedroomPrice = 0;
    $('input').on('change', function() {
        if ($(this).is(':checked')) {
            bedroomPrice = $('input[name="bedrooms"]:checked').data('price');
        } else {
            bedroomPrice = 0;
        }
        $('#total').html(bedroomPrice);
    });
});

希望它對你有用。

暫無
暫無

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

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