如何使用jQuery修改sp-pcp-post块内.pcp-readmore-link的href属性
问题原因
- DOM查找范围错误:你代码中遍历的是
.sp-pcp-title节点,而目标元素.pcp-readmore-link不在.sp-pcp-title的后代节点范围内,二者是同属于.sp-pcp-post下的平级节点的子元素,find()方法只能查找当前节点的后代,因此完全找不到目标链接,无法修改属性。 - 文本匹配容错不足:直接调用
.text()获取的内容会包含HTML结构带来的换行、前后空白字符,大概率无法和switch中写死的固定文本匹配上。
修复后的实现代码
建议用映射表替代冗余的switch分支,后续新增修改规则只需维护映射表即可,代码更易维护:
// 标题文本与目标跳转链接的映射规则 const titleLinkMap = { "Machines": "/product-category/machines/", "Weights": "/product-category/weights/", "Dumbells": "/product-category/dumbells/", "Barbels": "/product-category/barbels/" }; // 遍历每个内容块批量处理 $(".sp-pcp-post").each(function() { // 去除标题文本前后的空白、换行符避免匹配失败 const currentTitle = $(this).find(".sp-pcp-title").text().trim(); // 匹配到规则后修改对应readmore链接的href if (titleLinkMap[currentTitle]) { $(this).find(".pcp-readmore-link").attr("href", titleLinkMap[currentTitle]); } });
如果你需要保留原有的switch写法,只需要调整遍历对象和查找范围即可:
$(".sp-pcp-post").each(function() { const $post = $(this); const title = $post.find(".sp-pcp-title").text().trim(); switch(title) { case "Machines": $post.find(".pcp-readmore-link").attr('href', '/product-category/machines/'); break; case "Weights": $post.find(".pcp-readmore-link").attr('href', '/product-category/weights/'); break; case "Dumbells": $post.find(".pcp-readmore-link").attr('href', '/product-category/dumbells/'); break; case "Barbels": $post.find(".pcp-readmore-link").attr('href', '/product-category/barbels/'); break; } });
内容的提问来源于stack exchange,提问作者calvincani
相关产品推荐
相关产品推荐

