如何仅当按钮href包含链接或句点时修改其值?
解决方法
你只需要在循环里增加判断逻辑,检查按钮的href属性是否包含URL特征(比如含http/https或者句点),符合条件再替换:
window.onload = function() { var anchors = document.getElementsByClassName("elementor-button"); for (var i = 0; i < anchors.length; i++) { const currentHref = anchors[i].href; // 判断href是否包含http/https(链接特征)或者句点 if (currentHref.includes('http') || currentHref.includes('.')) { anchors[i].href = "https://google.com"; } } }
关键说明
- 使用
includes()方法检查当前href是否包含指定字符串:currentHref.includes('http'):匹配带协议的标准URL(比如https://xxx.com)currentHref.includes('.'):匹配可能不带协议但含句点的链接(比如xxx.com)
- 只有满足其中一个条件时,才会替换
href为目标链接,避免修改不符合要求的按钮。
如果需要更精准的URL匹配,可改用正则表达式替代简单的字符串判断,避免误判含句点但非网页链接的情况:
window.onload = function() { var anchors = document.getElementsByClassName("elementor-button"); // 匹配标准网页URL的正则 const urlRegex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/; for (var i = 0; i < anchors.length; i++) { const currentHref = anchors[i].href; if (urlRegex.test(currentHref)) { anchors[i].href = "https://google.com"; } } }
内容的提问来源于stack exchange,提问作者Guilherme Torres
相关产品推荐
相关产品推荐

