当前位置路径作为url参数

时间:2017-05-24 14:15:22

标签: javascript jquery surveymonkey

我需要将公司网站上的链接放到调查密钥调查中。我们的网站使用专有的CMS限制我添加任何适当的功能或第三方插件。

在评估this other question中公开的选项之后,我相信我调用了正确的javascript函数,但每次打开我的CMS时,链接都会重复...导致我认为我做了一些不合适的事情。 / p>

the JSFiddle demo我在这个问题上总结了一些事情,但是我希望你能有一个更优雅的解决方案,所以我可以尝试选择!

<script type="text/javascript">
document.write("<a href='https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname + " target='_blank'>Test - survey</a>");
</script>

2 个答案:

答案 0 :(得分:2)

试试这个 - 它可能不会一气呵成,但它有望隔离你的问题,以便你可以更好地查明出错的地方:

HTML:

<div id="link"></div>

使用Javascript:

var SURVEYID = 3
var a = document.createElement("a");

a.innerHTML = "Test - survey";
a.href = "www.surveymonkey.com/r/" 
  + SURVEYID 
  + "?url=" 
  + window.location.pathname 
  + "&target=_blank"

document.getElementById("link").appendChild(a)

我担心会出现多种问题,但我希望您现在可以区分构建网址的各个部分。

答案 1 :(得分:1)

这主要只是一个理论,因为我不知道您的CMS或它是如何工作的,但我假设CMS正在内联javascript,执行它,并将其作为内容与脚本一起保留。这会产生重复。我假设使用document.write的初衷是完全替换内容;但如果它是内联的,它只会附加。外部脚本将完全替换。见下文:

All of this text is retained.
<script type="text/javascript">
document.write("<a href='https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname + "' target='_blank'>Test - survey</a>");
</script>

在本演示中,我们使用document.body.innerHTML代替。这将完全取代内容。

None of this text will be retained.
<script type="text/javascript">
document.body.innerHTML = "<a href='https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname + "' target='_blank'>Test - survey</a>";
</script>

如果属实,完全替换身体内容是您的目标,innerHTML可能就是您所需要的。

编辑+警告:

这可能会使CMS无法访问页面,具体取决于它的构建方式。它可能使编辑页面变得不可能。

修改

这是一个更好的解决方案。只需先通过ID获取锚点的href即可。这是基于Sven ten Haaf's Answer

<a href="#" id="__smlink" target='_blank'>Test - survey</a>
<script>
	document.getElementById('__smlink').href = "https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname;
</script>