標題重寫:強調頁面上特定值的技術
P粉588152636
P粉588152636 2023-09-05 09:37:49
0
1
486
<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學習者快速成長!