Title Rewriting: A Technique for Emphasizing Specific Values on a Page
P粉588152636
2023-09-05 09:37:49
<p>For example, on a site like</p>
<p>How can I code to highlight any price above 20€ in red in the product grid? Also, I need it to keep working even if the user selects/deselects a category on the right. </p>
<p>Is this 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>
ReferencedWebsite Filters prices by displaying only those that fit within a user-defined range, while removing any prices that are not within the price range. The filter you requested only highlights anything above 20. Additionally, the second request:
Can't answer because you haven't posted any code involving any other filters.
Regarding the posted code, it fails not only on syntax, but also on purpose.
jQuery methods do not recognize plain JavaScript references and vice versa. In order to use pure JavaScript methods on a jQuery object, the jQuery object must be dereferenced. Avoid chaining jQuery and JavaScript methods. Here is the jQuery method table and pure JavaScript method table used in the question:
jQuery method
Pure JavaScript method
In short, a jQuery object consisting of
div.mErEH _223RA
is created through.each()
and.find()
The code>. Then when.sort()
is called on the jQuery object, the function fails because:.sort()
is a normal JavaScript method and does not recognize jQuery objects.sort()
handles arrays, jQuery objects do notIf the function abandons jQuery entirely and just collects all
div.mErEH _223RA
as a NodeList and then converts to an array,.sort()
and.slice ()
can work. Unfortunately, the new array returned consists of the first 6 DOM elements in ascending order, which doesn't even allow you to highlight all DOM elements beyond 20.In the following example, the actual HTML layout is irrelevant, className
".x"
should be replaced with".mErEH _223RA"
.Details are commented in the examples