标题重写:强调页面上特定值的技术
P粉588152636
P粉588152636 2023-09-05 09:37:49
0
1
484
<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>
P粉588152636
P粉588152636

全部回复(1)
P粉315680565

引用的网站通过仅显示符合用户定义范围的价格来过滤价格,同时删除任何不在价格范围内的价格。您请求的过滤器仅突出显示超过 20 的任何内容。此外,第二个请求:

无法回答,因为您尚未发布任何涉及任何其他过滤器的代码。

关于发布的代码,它不仅在语法上失败,而且在目的上也失败。

  1. jQuery 方法无法识别纯 JavaScript 引用,反之亦然。为了在 jQuery 对象上使用纯 JavaScript 方法, jQuery 对象必须取消引用。避免链接 jQuery 和 JavaScript 方法。下面是问题中使用的 jQuery 方法表和纯 JavaScript 方法表:

    • jQuery 方法

      方法 描述
      .each()
      迭代 jQuery 对象并为每个 DOM 元素调用函数
      .find()
      收集 jQuery 对象中所有指定的 DOM 元素作为新的 jQuery 对象
      .addClass()
      向 jQuery 对象中的每个 DOM 元素添加一个类
    • 纯 JavaScript 方法

      方法 描述
      .sort()
      按升序返回给定数组的新副本
      .slice()
      将给定数组中定义的元素范围作为新数组返回
    • 简而言之,由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>
热门专题
更多>
热门文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!