在HTML中使用Javascript变量<;a>;链接

在HTML中使用Javascript变量<;a>;链接,javascript,html,Javascript,Html,我的代码是这样的- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title>

我的代码是这样的-

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>


    <script type='text/javascript'>

    var random_generator;
    document.write('Random Selection: ');
    var arr=['One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten'];
    var randomnumber=Math.floor(Math.random()*10);
    random_generator=arr[randomnumber];
    document.write(random_generator+ '<br>');


    </script>

<style type="text/css">

</style>
<a href='www.xyz.com/Index1/Index2/Variable/Index4'>Good Morning</a>
</head>
<body> 
</body>  
</html>

无功随机发生器;
文件。写入('随机选择:');
var arr=[‘一’、‘二’、‘三’、‘四’、‘五’、‘六’、‘七’、‘八’、‘九’、‘十’];
var randomnumber=Math.floor(Math.random()*10);
随机_生成器=arr[随机数];
文件写入(随机生成器+“
”);
我想使用random_generator Javascript变量代替标记中的变量。我该怎么做?提前谢谢


注意:随机_生成器不会替换整个链接。仅链接的一部分(/Variable/)。根据此值,将向用户显示不同的页面。

您可以在执行脚本时使用jQuery更新dom元素

首先,您必须为href提供一个id


这肯定会有用的

   document.getElementById('myHref').href = variable;

据我所知,这是不可能的。您可以做以下两件事之一:

1在加载文档时更改HREF属性。使用JQuery,您可以执行以下操作

$(function() {
 $('a').attr('href', 'www.xyz.com/Index1/Index2/' + random_generator + '/Index4');
});
2捕获点击事件并用javascript重定向它,这意味着即使用户多次点击链接而不刷新页面,它也是随机的

$(function() {
 $('a').on('click', function(e) {
   e.preventDefault();
   window.location = 'www.xyz.com/Index1/Index2/' + random_generator + '/Index4';
 });
});

如果您不希望使用jquery,我相信在线上有很多使用纯javascript的例子。

我不确定是否理解您的问题。但是,如果您试图动态地将链接设置为href(假设您没有使用jquery),那么以下操作应该可以使用


var newUrl=document.getElementById('index').href;
newUrl=newUrl.replace(“变量”,随机_生成器);
document.getElementById('index')。href=newUrl;

或者您可以将链接编写为内联js

​<script>
document.write('<a href="http://www.xyz.com/Index1/Index2/' + random_generator + '/Index4">hello</a>');
</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
​
文件。写(“”);
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

是否替换href或文本?抱歉,我弄糊涂了。请替换href链接中的变量。不同的地址链接取决于href标记中变量(/Variable/)的值。非常抱歉。我错过了。感谢您的耐心。或者只是document.getelementbyidy您的意思是
$('#myHref').attr('href',variable)
?感谢您的回复。非常感谢。
​<script>
document.write('<a href="http://www.xyz.com/Index1/Index2/' + random_generator + '/Index4">hello</a>');
</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​