从Javascript返回值为HTML <a href=""> tag

时间:2016-01-20 19:57:27

标签: javascript html

I have html code like this:

<a id="abc_1" name="link_1" href=""
                    onclick="updateLink(this.id);">Test Link</a>

My Javascript function is like this:

function updateLink(a){ 
 var newurl = document.location.href "+" + a.valueOf();
 return newurl;
}

I want to direct the user to this newurl on click of link. How to do it? Note: I have seen an example with use of <div> tag, but I need it in <a href> tag.

2 个答案:

答案 0 :(得分:1)

一种方法是从点击处理程序

更改href属性

    window.updateLink = function (a){
       // This won't work in this example because this frame
       // is set 'X-Frame-Options' to 'SAMEORIGIN'.
       // However, the error message displayed in the console is indication 
       // that it indeed tried to navigate to the URL I gave it 
       a.setAttribute('href', 'http://www.google.com?q=' + a.id);
    }
<a href="#" id="http://www.google.com" onclick="updateLink(this)" >Test</a>

答案 1 :(得分:1)

我假设锚属性id或名称包含有关新URL的信息。

看看这个例子:

<a href="#" id="abc_1" name="link_1" onclick="updateLink(this)" >Test Link</a>

<script>
function updateLink(a) {
  var newurl = "";

  //You could retrieve the object name
  newurl = a.getAttribute("name");

  //Or, retrieve the id
  newurl = a.getAttribute("id");

  //redirect 
  location.href = newurl;
}
</script>
相关问题