<p>例如,在这样的网站上</p>
<p>我如何编码才能在产品网格中突出显示任何高于 20 欧元的红色价格?另外,即使用户选择/取消选择右侧的类别,我也需要它继续工作。</p>
<p>这是 JavaScript 吗?</p>
<pre class="brush:php;toolbar:false;">$('div').each(function() {
$(this).find('.mErEH _223RA').sort(function(a, b) {
return b.innerText - a.innerText;
}).slice(0, 5).addClass('higherthan20')
});</pre>
<pre class="brush:php;toolbar:false;">.higherthan20 {
color: red;
}</pre></p>
引用的网站通过仅显示符合用户定义范围的价格来过滤价格,同时删除任何不在价格范围内的价格。您请求的过滤器仅突出显示超过 20 的任何内容。此外,第二个请求:
无法回答,因为您尚未发布任何涉及任何其他过滤器的代码。
关于发布的代码,它不仅在语法上失败,而且在目的上也失败。
jQuery 方法无法识别纯 JavaScript 引用,反之亦然。为了在 jQuery 对象上使用纯 JavaScript 方法, jQuery 对象必须取消引用。避免链接 jQuery 和 JavaScript 方法。下面是问题中使用的 jQuery 方法表和纯 JavaScript 方法表:
jQuery 方法
纯 JavaScript 方法
简而言之,由
div.mErEH _223RA组成的jQuery对象是通过.each()和.find()创建的代码>.然后,当在所述 jQuery 对象上调用.sort()时,该函数会失败,因为:.sort()是一个普通的 JavaScript 方法,无法识别 jQuery 对象.sort()处理数组,而 jQuery 对象则不然如果该函数完全放弃 jQuery,只收集所有
div.mErEH _223RA作为 NodeList,然后转换为数组,.sort()和.slice()可以工作。不幸的是,返回的新数组由按升序排列的前 6 个 DOM 元素组成,这甚至无法突出显示超过 20 个的所有 DOM 元素。在以下示例中,实际的 HTML 布局无关紧要,className
".x"应替换为".mErEH _223RA"。示例中注释了详细信息
/** * For each ".x"... */ $(".x").each(function() { /** * ...get it's text with .textContent. * Then exclude the first character ("€") with .substring(1)... * ...and convert the text into a real number with Number(). */ let price = Number(this.textContent.substring(1)); /** * Next, if the number is greater than 20... */ if (price > 20) { /** * ...add ".red" className to DOM element. */ $(this).addClass("red"); } });.red { color: red }<main> <table> <tbody> <tr><td class="x">€20</td><td class="x">€100</td><td class="x">€10</td></tr> <tr><td class="x">€55</td><td class="x">€2</td><td class="x">€2000</td></tr> <tr><td class="x">€8</td><td class="x">€325</td><td class="x">€120</td></tr> <tr><td class="x">€70</td><td class="x">€99</td><td class="x">€220</td></tr> <tr><td class="x">€19</td><td class="x">€25</td><td class="x">€440</td></tr> <tr><td class="x">€111</td><td class="x">€44</td><td class="x">€13</td></tr> </tbody> </table> </main> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>