jQuery .text() 不检索元素文本

问题描述 投票:0回答:1

我有这个 HTML 并且文本是动态生成的:

<span class="amount">1790.00</span>

我的问题是我无法检索 span 标签的文本。这是我的 jQuery 代码:

$(document).ready(function() {
    displayProductData(); 
    displayTotalAmount();
        
    function displayProductData() {
        $.ajax({
            url: `<?=base_url(""); >ProductsController/fetch_product_details/${productId}`,
            type: "GET",
            dataType: "json",
            success: function(response) {
                console.log(response);
                $.each(response.productData, function (index, product) {
                    let image_path = "<?=base_url('');?>" + product.image_url;
                    $('.product_name').html(product.name);
                    /*NOTE: This displays the price which is 1790.00*/
                    $('.amount').text(product.price);
                    $('.description').html(product.description);
                    $('.product_thumbnail').prepend(`<img src='${image_path}' alt="food">`);
                    $('#product_id').val(product.product_id);
                })
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log('AJAX Error:', textStatus, errorThrown);
            }
        })
    function displayTotalAmount() {
        let quantity = $('#quantity').val();
        console.log('quantity:', quantity);
        /* This should log '1790.22' to the console */
        console.log("Amount: " + $(".amount").text()); 
    }
}

浏览器的输出: enter image description here

jquery
1个回答
-1
投票

问题是因为您使用的选择器是类选择器: $(".amount").text()

此代码将返回所有具有“amount”类的对象的数组。

所以你必须在金额上添加一个 id 或类似 $(".amount")[0].text()

© www.soinside.com 2019 - 2024. All rights reserved.