我有这个 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());
}
}
问题是因为您使用的选择器是类选择器: $(".amount").text()
此代码将返回所有具有“amount”类的对象的数组。
所以你必须在金额上添加一个 id 或类似 $(".amount")[0].text()