我已经说过一遍又一遍,但我还是要再说一遍:JavaScript 在 Web 应用程序中的主要作用是增强浏览器提供的其他无聊的静态功能。一个完美的例子是过去五年流行的基于 Javascript/AJAX 的星级评定系统。星级评分系统很有吸引力,可以让我们避免丑陋的形式,并防止不必要的页面重新加载。 Lorenzo Stanco 开发的一个名为 MooStarRating 的新插件已登陆 MooTools Forge,我想与您分享如何使用它。
HTML
星级评分系统使用以单选按钮为基础的 HTML 表单:
<form name="ratingsForm"> <label>Do you like this post?</label> <input type="radio" name="rating" value="0.5"> <input type="radio" name="rating" value="1.0"> <input type="radio" name="rating" value="1.5"> <input type="radio" name="rating" value="2.0"> <input type="radio" name="rating" value="2.5"> <input type="radio" name="rating" value="3.0"> <input type="radio" name="rating" value="3.5"> <input type="radio" name="rating" value="4.0"> <input type="radio" name="rating" value="4.5"> <input type="radio" name="rating" value="5.0"> <input type="radio" name="rating" value="5.5"> <input type="radio" name="rating" value="6.0"> <input type="radio" name="rating" value="6.5"> <input type="radio" name="rating" value="7.0" checked="checked"> <input type="radio" name="rating" value="7.5"> <input type="radio" name="rating" value="8.0"> <input type="radio" name="rating" value="8.5"> <input type="radio" name="rating" value="9.0"> <input type="radio" name="rating" value="9.5"> <input type="radio" name="rating" value="10.0"> <span id="htmlTip"></span> </form>
注意表单的 ID 和单选按钮的名称——我们将在创建 MooStarRating 实例时使用它们。另请注意,我正在创建“半”评级选项,并使用选中来记录当前的平均评级。
CSS
这个插件不需要额外的 CSS。这是一个额外的好处,因为它减少了一个服务器请求。
MooTools JavaScript
使用 MooStarRating 的第一步是定义星星的图像路径:
// Configure the image paths var MooStarRatingImages = { defaultImageFolder: "/js/mooStarRating/images", defaultImageEmpty: "empty.png", defaultImageFull: "full.png", defaultImageHover: "hover.png" };
一旦定义了路径和图像名称,就可以创建 MooStarRating 的实例了:
// A fake post ID for the sake of submission var postId = 10; // When the DOM is ready.... window.addEvent("domready",function() { // Create our instance var starRater = new MooStarRating({ form: "ratingsForm", radios: "rating", half: true, //imageEmpty: "star_boxed_empty.png", // For setting special images //imageFull: "star_boxed_full.png", //imageHover: "star_boxed_hover.png", width: 17, tip: "Rate as <i>[VALUE] / 10.0</i>", tipTarget: document.byId("htmlTip"), tipTargetType: "html" }); // Listen for star clicks starRater.addEvent("click",function(value) { // Send ajax request to server new Request.send({ url: "rating.php", data: { rating: value, postId: postId } }); }); });
MooStarRating 加载了选项。在这里,我们将表单 ID 和我们提供给单选按钮的名称传递给它们。因为我允许半星,所以 half
选项设置为 true。 MooStarRating 还提供了一个“提示”功能,允许在星级旁边显示一条消息。最后,click
事件提供了用户的评级,您可以向服务器发送 AJAX 请求以保存评级。很简单!
就是这样!我喜欢这个插件,因为它简单有效。洛伦佐·斯坦科 (Lorenzo Stanco) 出色的作品值得大力支持。如果有足够的兴趣,我将创建一个教程,其中包含足够的 PHP 和 MySQL 来让这个评级系统使用真实数据。