javascript - jQuery:按类选择元素返回 jQuery.fn.init(9) - 无法读取 .val()

标签 javascript jquery arrays

我尝试使用以下代码获取具有特定类名的所有元素:

productPrices = $('.product-price');

但是这正在返回:

jQuery.fn.init(9) [div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, prevObject: jQuery.fn.init(1)]

我相信这就是为什么我无法访问每个索引的值的原因;当我尝试执行此代码时:

    // Clone original prices
for(var i = 0; i < productPrices.length; i++) {
    productPrices[i].val().replace("£", "");
    console.log(productPrices[i].textContent);
    britishPrices[i] = productPrices[i].textContent;
}

我收到以下错误:

productPrices[i].val is not a function

正如我所说,我相信这是由选择类值时奇怪的返回值引起的。我也尝试过使用 .text() 和 .html() 。

如果有人能帮助我理解这一点,我将非常感激。

最佳答案

productPrices[i]

应该是

productPrices.eq(i)

jQuery 对象上的括号表示法将 DOM 元素从结果堆栈中分离出来,它不再是 jQuery 对象,而 val() 是其方法。要将其保留为 jQuery 对象,请改用 eq(#)

关于javascript - jQuery:按类选择元素返回 jQuery.fn.init(9) - 无法读取 .val(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56067814/

相关文章:

Javascript自动播放声音文件,单击其中一个按钮时停止

jQuery 根据下拉菜单显示内容

php - 使用 jquery/css3 在语音气泡中显示错误消息

javascript - 对数组项进行排序并保留相同元素的顺序

javascript - 循环遍历 JS 对象数组以获取特定属性

javascript - 自动化网络分析测试过程

javascript - 一个html页面上多个页面的下拉菜单

javascript - 如何解决 "Cross-Origin Request Blocked"错误?

jquery - fancybox 2.0.4 和 Vimeo

java - 计算cardSum(字符串之手)