简体   繁体   English

Javascript将变量连接到url

[英]Javascript concatenate variable to url

If i have a variable lets say 如果我有变量可以说

var id = //something dynamically generated 
then i have <a href="http://localhost/ (the variable id)"

How do i go about this? 我该怎么做?

The concatenation cannot occur within the anchor tag itself, but you can set it like this: 连接不能在锚标记本身内发生,但您可以像下面这样设置:

<a id="my_anchor" href=""></a>

<script type="text/javascript">

    // jQuery way
    $( "#my_anchor" ).attr( 'href', 'http://localhost/' + id );

    // Non-jQuery way
    document.getElementById( "my_anchor" ).href = 'http://localhost/' + id;

</script>

Suppose: 假设:

<a id="yourLink" href="http://localhost/ (the variable id)" />

Plain JavaScript 简单的JavaScript

document.getElementById('yourLink').href += id;

or in jQuery 或者在jQuery中

$('#yourLink').attr('href', function() {
  return this.href + id;
});

Something like this: 像这样的东西:

<a href="#" id="mylink">My Link</a>

var id = // something dynamic
var url = "http://localhost/"+id;

document.getElementById("mylink").href = url;

You don't have to wait for the document to have fully loaded, in most cases as long as the element has been loaded into the DOM you will be fine assuming that your Javascript is placed after the element (like above). 您不必等待文档完全加载,在大多数情况下,只要元素已加载到DOM中,您就可以假设您的Javascript放在元素之后(如上所述)。

Not good practice, but it's misleading to say you "have" to wait for the whole page to be loaded. 不是很好的做法,但是说你“等待”整个页面被加载是误导的。 You don't. 你没有。

Nobody has pointed out you should always do encodeURIComponent when you set things like this; 当你设置这样的东西时,没有人指出你应该总是做encodeURIComponent ; otherwise you leave yourself open to script injection attacks: 否则你会对脚本注入攻击开放:

Taking @jayp's example: 以@jayp为例:

<a href="#" id="mylink">My Link</a>

var id = getSomethingDynamic();
var url = "http://localhost/" + encodeURIComponent(id);

document.getElementById("mylink").href = url;

Try this one, I used this 尝试这个,我用过这个

<script type="text/javascript">
    var id = 2; //something dynamically generated
    <a href='http://localhost/edit.php?catID "+id+" '>
<script>

Javascript function: Javascript功能:

function openUrl(id)
{
 window.location = "http://localhost/"+id
}

html: HTML:

<a href="javascript:void(0)" onclick="openUrl(id)">link</a>

You can just retrieve the DOM element, and add something to the href property. 您可以只检索DOM元素,并向href属性添加内容。 Like this: 像这样:

<script type='text/javascript'>

var id = 5;

window.onload = function()
{
    document.getElementById('url').href += id;
}

</script>

<a href='http://localhost/?id=' id='url'>Click me</a>

You have to wait for the document to load in order to get the element, it would not exist otherwise. 您必须等待文档加载才能获取元素,否则它将不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM