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

如何使用Javascript/jQuery将图片URL和标题传入按钮链接

解决方案

jQuery 实现

通过遍历每个产品项,提取对应图片地址和标题,动态生成带参数的链接即可批量完成设置,代码如下:

$(document).ready(function() {
  $('.product-item').each(function() {
    const $item = $(this);
    // 提取当前产品项里的图片地址
    const imgSrc = $item.find('img').attr('src');
    // 提取产品标题并去除首尾空白
    const productTitle = $item.find('h3').text().trim();
    // 获取按钮元素
    const $button = $item.find('.button');
    // 构造编码后的链接(避免空格/特殊字符破坏URL结构)
    const href = `/inquiry?image=${encodeURIComponent(imgSrc)}&title=${encodeURIComponent(productTitle)}`;
    // 把按钮内容替换为带链接的a标签
    $button.html(`<a href="${href}">${$button.text().trim()}</a>`);
  });
});

原生 JavaScript 实现

如果不想依赖jQuery,用原生JS也能实现同样效果:

document.addEventListener('DOMContentLoaded', function() {
  const productItems = document.querySelectorAll('.product-item');
  productItems.forEach(item => {
    // 提取图片地址
    const imgSrc = item.querySelector('img').src;
    // 提取产品标题
    const productTitle = item.querySelector('h3').textContent.trim();
    const button = item.querySelector('.button');
    // 构造编码后的链接
    const href = `/inquiry?image=${encodeURIComponent(imgSrc)}&title=${encodeURIComponent(productTitle)}`;
    // 创建a标签并替换按钮内容
    const link = document.createElement('a');
    link.href = href;
    link.textContent = button.textContent.trim();
    button.innerHTML = '';
    button.appendChild(link);
  });
});

关键提示

  • 必须用encodeURIComponent对参数编码,否则标题里的空格、特殊字符会导致URL解析错误
  • 确保代码在DOM加载完成后执行,否则找不到页面元素
  • 如果图片src是绝对路径,编码后会保留完整路径;若只需要相对路径,可以自行处理imgSrc的值

内容的提问来源于stack exchange,提问作者R. Guan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 20:00:00