最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript concatenate variable to url - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Oct 14, 2011 at 12:37 user951042user951042 0
Add a comment  | 

7 Answers 7

Reset to default 7

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

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

or in jQuery

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

Nobody has pointed out you should always do encodeURIComponent when you set things like this; otherwise you leave yourself open to script injection attacks:

Taking @jayp's example:

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

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

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

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).

Not good practice, but it's misleading to say you "have" to wait for the whole page to be loaded. You don't.

Javascript function:

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

html:

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

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>

You can just retrieve the DOM element, and add something to the href property. 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.

发布评论

评论列表(0)

  1. 暂无评论