我希望href由一个在javascript中设置的变量组成,我还需要在页面上显示的文本是一个变量。在下面的例子中,我希望将字符串"http://google.com“赋给一个变量,我也需要有”我的链接名称“作为变量。我在这里看过类似的问题,但我看不出是什么解决了这种特殊情况。
<a href="http://google.com">Go Here Now</a><br>
在下面的示例中,我可以创建一个名为myLinkName的变量并将其设置为字符串"Go here now“,但是我不知道如何创建一个变量并将其设置为href的值,例如"http://google.com”
<script type="text/javascript">
var myLinkName = "Go Here Now";
</script>
<a href="http://google.com">
<script type="text/javascript">
document.write(myLinkName)
</script></a>
发布于 2019-05-09 01:17:32
我担心您正在使用一些非常古老的JavaScript材料。
描述了document.write()的用法。您正在遵循的方法是过时的。今天,JS没有被评估,只是被写入到文档中。相反,文档是显式操作的。
首先:<script>
足以声明一些JavaScript。不再需要type属性。
<a id=myLink></a>
<script>
//get a reference to the a element
const myLink = document.getElementById("myLink");
//set the text
myLink.innerText = "Click me!";
//set href
myLink.href = "http://google.com";
</script>
发布于 2019-05-09 01:02:36
您必须使用DOM
HTML
<a id="aLink"></a>
Javascript
let link = document.getElementById('aLink');
link.href = "https://google.com";
link.innerText = 'This is my Link'
完整的代码:
<html>
<body>
<a id="aLink"></a>
<script>
let link = document.getElementById('aLink');
link.href = "https://google.com";
link.innerText = 'This is Link';
</script>
</body>
</html>
发布于 2019-05-09 01:02:13
可以像这样设置href属性
var text = 'Go Here Now';
var href = 'http://google.com'
var atag = document.getElementsByTagName('a')[0];
atag.innerText = text;
atag.href = href;
var text = 'Go Here Now';
var href = 'http://google.com'
var atag = document.getElementsByTagName('a')[0];
atag.innerText = text;
atag.href = href;
<a href=""></a><br>
https://stackoverflow.com/questions/56045590
复制相似问题