如何排除具有特定href的锚标记?

时间:2019-08-29 22:24:45

标签: javascript jquery dom

我有一个采用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;
      }
    });
})();


因此它将搜索每个锚标记,并且在页面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

1 个答案:

答案 0 :(得分:4)

您可以尝试在querySelectorAll上使用attribute selector,如下所示:

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

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

您当然可以尝试根据需要进行修改。