javascript – 使用jQuery在页面加载时将字符串添加到url?

前端之家收集整理的这篇文章主要介绍了javascript – 使用jQuery在页面加载时将字符串添加到url?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在页面加载时将此特定字符串添加到我的URL的末尾:

?aa_campaign = f45632

(http://examplesite.com/test.html)

它用于营销和跟踪.

我试过这个:

if window.location.href.indexOf("http://examplesite.com/test.html") {
  window.location = "http://examplesite.com/test.html?aa_campaign=f45632";
}

直接上升不起作用,但这个想法是我正在寻找的.有什么想法吗?

解决方法

不需要jQuery,你可以在大多数“现代”浏览器中用纯JavaScript做到这一点,即:
if (window.location.href  === "http://examplesite.com/test.html") {
    window.history.pushState("object or string","Title","http://examplesite.com/test.html?aa_campaign=f45632");
}

pushState()方法

pushState() takes three parameters: a state object,a title (which is
currently ignored),and (optionally) a URL. Let’s examine each of
these three parameters in more detail:

06001

the user navigates to the new state,a popstate event is fired,and
the state property of the event contains a copy of the history entry’s
state object.

06002

after the user restarts the browser,we impose a size limit of 640k
characters on the serialized representation of a state object. If you
pass a state object whose serialized representation is larger than
this to pushState(),the method will throw an exception. If you need
more space than this,you’re encouraged to use sessionStorage and/or
localStorage.

06003

against future changes to the method. Alternatively,you could pass a
short title for the state to which you’re moving.

06004

pushState(),but it might attempt to load the URL later,for instance
after the user restarts the browser. The new URL does not need to be
absolute; if it’s relative,it’s resolved relative to the current URL.
The new URL must be of the same origin as the current URL; otherwise,
pushState() will throw an exception. This parameter is optional; if it
isn’t specified,it’s set to the document’s current URL.

SRC:https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

原文链接:https://www.f2er.com/jquery/158833.html

猜你在找的jQuery相关文章