首先,让我为在这里成为一个完整的新手而道歉。我13年前参加了一个Javascript课程,似乎已经忘记了大部分课程。无论如何,我在网上找到了一些代码,可以动态地在我们的网页上添加通过我们的Google广告通过网址发送的关键字。我正在使用Jimdo创建一个免费网站,它们允许您向Body添加代码,但不确定是否可以添加到Head。无论如何,当我将下面的代码添加到Body时,没有任何反应。为了工作,应该放置这些代码的内容,地点和方式?
示例:http://www.yourdomain.com?utm_term= {keyword}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split(“&”);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split(“=”);
if (pair[0] == variable) {
return pair[1];
}
}
}
searchTerms = getQueryVariable(‘utm_term’);
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/+/g, ” “);
searchTerms = unescape(searchTerms);
document.write(“<h1>This headline is about ” + searchTerms + “</h1>”);
}
else {
document.write(“<h1>This headline is generic.</h1>”);
}
答案 0 :(得分:1)
这里是小提琴:http://jsfiddle.net/dnd4kepr/
有两个问题:
单/双左/右引号(“&”
)(或花哨的引号)抛出异常。你只想用简单的单/双引号("&"
)替换那些坏男孩。
一旦更换了花哨的引号,由于正则表达式引发了异常。您想要逃避+
字符,如下所示:searchTerms = searchTerms.replace(/\+/g, ' ');
完成这两件事之后,脚本就开始工作了!
答案 1 :(得分:1)
<script type="text/javascript">
//<![CDATA[
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
}
searchTerms = getQueryVariable('utm_term');
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/\+/g, ' ');
searchTerms = unescape(searchTerms);
write('<h1>This headline is about' + searchTerms + '</h1>');
}
else {
write('<h1>This headline is generic.</h1>');
}
}, false)
//]]>
</script>
答案 2 :(得分:0)
看一看!
(function() {
'use strict';
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var terms = getParameterByName('utm_term')
var h1 = document.createElement('H1');
/*
or if you want to hook to existing el
var h1 = document.getElementByTagName('h1');
if there is only one `h1` on the page
and remove document.body.appendChild(h1) at the end
*/
if (terms) {
var searchTerms = terms.replace(/\+|\,/g, " "); // not sure how you want to format
h1.innerText = "This headline is about " + searchTerms;
} else {
h1.innerText = "This headline is generic."
}
document.body.appendChild(h1);
})();
&#13;
你的html中已经有<h1>
吗?如果是这样,那么您应该使用jquery或vanilla js访问它,然后在该el上执行innerText
。让我知道,我将编辑我的答案。