You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

仅使用jQuery的Ajax与选择器,能否用精简原生JS替代完整库?

Replacing jQuery’s Ajax & Selector/Event Features with Vanilla JavaScript

Absolutely! You can ditch the full jQuery library and replace the specific features you’re using with plain JavaScript—it’s straightforward and will save your users from loading unnecessary code. Let’s walk through each part you mentioned:

1. Replacing $.ajax() with Native Fetch API

The modern replacement for jQuery’s Ajax is the Fetch API (it works in all modern browsers, and you can add a simple polyfill if you need to support older ones). Here’s how to map your existing code:

Your jQuery Code:

$.ajax({
  url: "dosomething.php",
  cache: 0,
  data: n,
  success: function(t) {
    // Handle the response here
  }
});

Equivalent Vanilla JavaScript:

// Add a timestamp to disable caching (matches jQuery's cache:0)
const url = new URL("dosomething.php");
if (n) {
  // Convert your data object to URL search parameters (for GET requests)
  Object.keys(n).forEach(key => url.searchParams.append(key, n[key]));
}
// Append a unique timestamp to bust cache
url.searchParams.append("_", Date.now());

fetch(url)
  .then(response => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    // Use response.text() for plain text, or response.json() if you expect JSON
    return response.text();
  })
  .then(t => {
    // This is your "success" callback logic
    console.log("Response received:", t);
  })
  .catch(error => {
    // Handle errors (jQuery's error callback equivalent)
    console.error("There was a problem with the request:", error);
  });

If you’re sending data via POST (instead of GET), adjust it like this:

fetch("dosomething.php", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded", // Matches jQuery's default content type
  },
  body: new URLSearchParams(n).toString(), // Convert data to form-encoded string
  cache: "no-store" // Disable caching
})
.then(response => response.text())
.then(t => {
  // Success logic here
})
.catch(error => {
  // Error handling here
});

2. Replacing Selectors & Event Handlers

Let’s cover each jQuery method you’re using with native alternatives:

a. $(document).ready(function() { ... })

This waits for the DOM to fully load. In vanilla JS, use the DOMContentLoaded event:

document.addEventListener("DOMContentLoaded", function() {
  // Your code that runs after the DOM is ready goes here
  initStarRating();
});

Pro tip: If you place your <script> tag at the end of the <body> (right before </body>), you don’t even need this—your code will run automatically after the DOM loads.

b. $(".stars").hover(function() { ... })

jQuery’s hover() combines mouseenter and mouseleave events. In native JS, bind both events separately:

// Get all .stars elements
const starElements = document.querySelectorAll(".stars");

starElements.forEach(star => {
  // Mouse enter (equivalent to hover's first function)
  star.addEventListener("mouseenter", function() {
    // Your hover-in logic here
    highlightStarsUpTo(this);
  });

  // Mouse leave (equivalent to hover's second function, if you used it)
  star.addEventListener("mouseleave", function() {
    // Your hover-out logic here
    resetStarHighlight();
  });
});

c. $(this).prevAll()

jQuery’s prevAll() gets all previous sibling elements. We can create a small helper function to replicate this in native JS:

function getPrevAll(element) {
  const siblings = [];
  let prevSibling = element.previousElementSibling;
  while (prevSibling) {
    siblings.push(prevSibling);
    prevSibling = prevSibling.previousElementSibling;
  }
  return siblings;
}

// Usage in your hover logic:
function highlightStarsUpTo(activeStar) {
  // Highlight the active star
  activeStar.classList.add("highlighted");
  // Highlight all previous stars
  const prevStars = getPrevAll(activeStar);
  prevStars.forEach(star => star.classList.add("highlighted"));
}

Full Example: Star Rating System in Vanilla JS

Putting it all together, here’s a complete snippet that mimics your star rating functionality:

document.addEventListener("DOMContentLoaded", function() {
  const starElements = document.querySelectorAll(".stars");
  let selectedRating = 0;

  // Hover and click logic for stars
  starElements.forEach(star => {
    star.addEventListener("mouseenter", function() {
      highlightStarsUpTo(this);
    });

    star.addEventListener("mouseleave", function() {
      resetStarHighlight();
      // Re-highlight selected rating if it exists
      if (selectedRating > 0) {
        const selectedStar = starElements[selectedRating - 1];
        highlightStarsUpTo(selectedStar);
      }
    });

    star.addEventListener("click", function() {
      selectedRating = Array.from(starElements).indexOf(this) + 1;
      submitRating(selectedRating);
    });
  });

  // Helper: Highlight star and all previous ones
  function highlightStarsUpTo(element) {
    element.classList.add("highlighted");
    let prevSibling = element.previousElementSibling;
    while (prevSibling) {
      prevSibling.classList.add("highlighted");
      prevSibling = prevSibling.previousElementSibling;
    }
  }

  // Helper: Reset all star highlights
  function resetStarHighlight() {
    starElements.forEach(star => star.classList.remove("highlighted"));
  }

  // Submit rating via Fetch (replaces $.ajax)
  function submitRating(rating) {
    const data = { rating: rating };

    fetch("dosomething.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams(data).toString(),
      cache: "no-store"
    })
    .then(response => response.text())
    .then(responseText => {
      // Handle success, e.g., update UI
      console.log("Rating submitted successfully:", responseText);
    })
    .catch(error => {
      console.error("Failed to submit rating:", error);
    });
  }
});

This code does everything your jQuery version did, without loading the full library. It’s lightweight, modern, and works in all current browsers.

内容的提问来源于stack exchange,提问作者Hookstark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:38:57