gpt4 book ai didi

javascript - 如何排除具有特定 href 的 anchor 标记?

转载 作者:行者123 更新时间:2023-11-29 17:34:53 24 4
gpt4 key购买 nike

我有一个采用 UTM 和其他 url 参数的 JS 代码,因此当用户在页面之间导航时,我不会丢失他们的踪迹。当 href 是一个页面但当它与 id 元素相关时,代码运行良好

我试过在if语句中排除或者在id后面加参数

function getRefQueryParam(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

var utmParamQueryString = '',
utmParamQueryStringTrimmed = '',
utm_source = '',
utm_medium = '',
utm_content = '',
utm_campaign = '',
utm_term = '';

(function() {
utm_source = getRefQueryParam("utm_source");
utm_medium = getRefQueryParam("utm_medium");
utm_content = getRefQueryParam("utm_content");
utm_campaign = getRefQueryParam("utm_campaign");
utm_term = getRefQueryParam("utm_term");
gclid = getRefQueryParam("gclid");
fbclid = getRefQueryParam("fbclid");

if (utm_source) {
utmParamQueryString += '&utm_source=' + utm_source;
}
if (utm_medium) {
utmParamQueryString += '&utm_medium=' + utm_medium;
}
if (utm_content) {
utmParamQueryString += '&utm_content=' + utm_content;
}
if (utm_campaign) {
utmParamQueryString += '&utm_campaign=' + utm_campaign;
}
if (utm_term) {
utmParamQueryString += '&utm_term=' + utm_term;
}
if (gclid) {
utmParamQueryString += '&gclid=' + gclid;
}
if (fbclid) {
utmParamQueryString += '&fbclid=' + fbclid;
}

if(utmParamQueryString.length > 0) {
utmParamQueryString = utmParamQueryString.substring(1);
utmParamQueryStringTrimmed = utmParamQueryString;
utmParamQueryString = utmParamQueryString;
}
if (!utmParamQueryString) return;
var navLinks = document.querySelectorAll('a');

navLinks.forEach(function(item) {
if (item.href.indexOf('/') === 0 || item.href.indexOf(location.host) !== -1 ) {
if (item.href.indexOf('?') === -1) {
item.href += '?';
} else {
item.href += '&';
}
item.href += utmParamQueryString;
}
});
})();


因此它会搜索每个 anchor 标记,并在页面 uri 之后插入当前 URL 具有的参数。问题是它插入代码,即使它是一个 id 调用 <a href="#top"></a>并且调用不再有效,因为参数不是插入之后而是介于两者之间,如下所示:utm_source=google&utm_medium=cpc&utm_campaign=test_cpc&utm_term=test #top &utm_source=google&utm_medium=cpc&utm_campaign=test_cpc&utm_term=test

最佳答案

你可以尝试使用attribute selector在你的 querySelectorAll 上像这样:

document.querySelectorAll('a:not([href^="#"])')

这将选择 href 属性不以 # 开头的所有 a 标签。

当然,您可以根据需要尝试修改它。

关于javascript - 如何排除具有特定 href 的 anchor 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57718396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com