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

能否进一步精简$.get()事件处理程序中的数据采集代码?

Optimizing Your jQuery Data Fetching Code

Absolutely—your code is full of repetitive boilerplate that we can strip away with loops and some smarter selectors. Let’s look at a few ways to tighten this up, starting with the simplest fixes and moving to more scalable approaches:

Basic Loop Reduction

First, we can eliminate duplicate lines by using for loops. We’ll also cache the parsed data object to avoid re-processing it multiple times (a small but useful performance win):

$.get('/blog.html', function(data) {
  const $data = $(data);
  
  // Handle post titles (7 items)
  for (let i = 1; i <= 7; i++) {
    $data.find(`.blog-post:nth-of-type(${i}) .blog-title`).appendTo(`.ticker-${i}`);
  }
  
  // Handle images and dates (5 items each)
  for (let i = 1; i <= 5; i++) {
    $data.find(`.blog-post:nth-of-type(${i}) img`).appendTo(`.ticker-image-${i}`);
    $data.find(`.blog-post:nth-of-type(${i}) .date`).appendTo(`.ticker-date-${i}`);
  }
});

This cuts down code length drastically while keeping logic clear. Template literals (${variable}) make selector building cleaner than messy string concatenation.

Scalable Configuration Object

If you might add more element types or adjust counts later, a configuration-based approach simplifies maintenance. We define mappings that tell the code what to move and where:

$.get('/blog.html', function(data) {
  const $data = $(data);
  
  // Define element mappings: source selector, target prefix, item count
  const elementMappings = [
    { source: '.blog-title', targetPrefix: '.ticker-', count: 7 },
    { source: 'img', targetPrefix: '.ticker-image-', count: 5 },
    { source: '.date', targetPrefix: '.ticker-date-', count: 5 }
  ];
  
  // Loop through mappings to process elements
  elementMappings.forEach(mapping => {
    for (let i = 1; i <= mapping.count; i++) {
      $data.find(`.blog-post:nth-of-type(${i}) ${mapping.source}`)
           .appendTo(`${mapping.targetPrefix}${i}`);
    }
  });
});

Now, adding new fields (like post excerpts) or adjusting counts only requires updating the elementMappings array—no more repetitive lines.

Iterate Directly Over Blog Posts

Another approach loops through each .blog-post element directly, mapping it to the corresponding ticker container by index. This avoids hardcoding counts upfront (we still check upper limits since titles go to 7 and others to 5):

$.get('/blog.html', function(data) {
  const $posts = $(data).find('.blog-post');
  
  $posts.each(function(index) {
    const postNumber = index + 1; // Convert 0-based index to 1-based number
    
    // Process titles for first 7 posts
    if (postNumber <= 7) {
      $(this).find('.blog-title').appendTo(`.ticker-${postNumber}`);
    }
    
    // Process images and dates for first 5 posts
    if (postNumber <= 5) {
      $(this).find('img').appendTo(`.ticker-image-${postNumber}`);
      $(this).find('.date').appendTo(`.ticker-date-${postNumber}`);
    }
  });
});

This works well if your blog posts are always in order and you want processing tied directly to the number of posts returned.

All these approaches maintain your original functionality while eliminating the repetitive code you were frustrated with. Pick the one that fits your future maintenance needs best!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:29:09