Javascript 使用jQuery在页面加载时向url添加字符串?

Javascript 使用jQuery在页面加载时向url添加字符串?,javascript,jquery,url,Javascript,Jquery,Url,我正在尝试在页面加载时将此特定字符串添加到url的末尾: ?aa_活动=f45632 () 它是用于营销和跟踪的 我试过这个: if window.location.href.indexOf("http://examplesite.com/test.html") { window.location = "http://examplesite.com/test.html?aa_campaign=f45632"; } 直接说没用,但这个想法正是我想要的。有什么想法吗?试试这个: if (win

我正在尝试在页面加载时将此特定字符串添加到url的末尾:

?aa_活动=f45632

()

它是用于营销和跟踪的

我试过这个:

if window.location.href.indexOf("http://examplesite.com/test.html") {
  window.location = "http://examplesite.com/test.html?aa_campaign=f45632";
}
直接说没用,但这个想法正是我想要的。有什么想法吗?

试试这个:

if (window.location.href.indexOf("http://examplesite.com/test.html" !== -1) {
  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()接受三个参数:状态对象、标题(即 当前已忽略),以及(可选)URL。让我们逐一检查一下 这三个参数更为详细:

state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever
用户导航到新状态,触发popstate事件,然后 事件的state属性包含历史记录项的副本 状态对象

The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored
在用户重新启动浏览器后,我们将大小限制为640k 状态对象的序列化表示形式上的字符。如果你 传递序列化表示形式大于的状态对象 如果将此设置为pushState(),则该方法将引发异常。如果你需要 如果空间大于此,建议您使用sessionStorage和/或 本地存储

title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe
针对该方法的未来更改。或者,你可以通过考试 您要迁移到的州的简短标题

URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to
pushState(),但它可能稍后尝试加载URL,例如 用户重新启动浏览器后。新的URL不需要 绝对的;如果是相对的,则相对于当前URL解析。 新URL必须与当前URL的来源相同;否则,, pushState()将引发异常。此参数是可选的;如果是 未指定,它设置为文档的当前URL


SRC:

您可以将字符串添加到
window.location.search
中,以获得更通用的解决方案

if(location.origin+location.pathname==='您的url在此'){
location.search+=“此处的其他数据”;

}
此版本将保留任何现有查询字符串,并正确附加“aa_campaign=f45632”参数字符串

var w = window.location;
if (w.search.indexOf("aa_campaign") == -1) {
    window.location = w + (w.search.indexOf("?") == -1 ? "?" : "&") + "aa_campaign=f45632";
}
例如:

  • -->

  • -->


这将是一个无限的重定向循环。你重定向到的URL仍然与indexOf CHECK匹配我已经更新了我的答案,它应该满足你的需要。看起来你在if之后是一个左括号,在第一行的第一个{之前是一个匹配的关闭括号。应该如下所示:
if(window.location.href.indexOf(“http://examplesite.com/test.html"))
谢谢:)工作得很好!