href属性中的document.write(变量)<a> tag

时间:2017-03-19 17:09:31

标签: javascript

due to the my lack of knowledges in javascript, i m here to please you to explain me why this line of code is not working properly, as it should do.

Firstly let me explain what I am trying to do and after that i will let you see my code. So, I'm using this guy script to check if adblock is active or not. https://stackoverflow.com/a/24111206

我使用adblock =“http://www。example1.tld”和adblock =“http://www更改adblock变量.example2.tld”。

我需要在&lt;的

 <script>document.write('<a href="<script> document.write(adblock)</script>"' + 'class="button-download popup">')</script>

有人可以解释一下在这种情况下该怎么做以及为什么我的代码无法正常工作?

1 个答案:

答案 0 :(得分:0)

您的代码无法正常运行,因为</script>表示脚本的结尾,无论脚本位于何处(在您的情况下,都在字符串内)。

但是,即使您修复了此问题,您的代码也无法正常工作,因为您无法将<script>标记放入锚标记的href属性中并期望它能够运行。如果要创建包含变量设置的URL的链接,可以使用document.createElement()执行此操作:

<script>
var a = document.createElement('a');
a.href = adblock;
a.className = 'button-download popup';
a.textContent = 'foo';

document.querySelector('#somewhere > foo').appendChild(a);
</script>

使用document.write() is usually bad practice。如果您坚持使用它,您可以像这样修改您的代码:

document.write('<a href="' + adblock + '" class="button-download popup">foo</a>');