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

Return value from Javascript to HTML <a href> tag - Stack Overflow

programmeradmin7浏览0评论

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.

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.

Share Improve this question edited Jan 25, 2016 at 13:59 Mr Lister 46.6k15 gold badges113 silver badges155 bronze badges asked Jan 20, 2016 at 19:57 User2403User2403 1851 gold badge4 silver badges15 bronze badges 5
  • 2 location.href = newurl should work – tymeJV Commented Jan 20, 2016 at 19:59
  • you aren't redirecting them with that function. like @tymeJV said you need to set the location.href of the page. – Devin Prejean Commented Jan 20, 2016 at 20:06
  • I removed return and tried location.href = newurl, but its not working, if I do alert(newurl), it shows the updated url but page is just getting refreshed. – User2403 Commented Jan 20, 2016 at 20:18
  • Yes you are correct. I found out my mistake, I havent used href="#". Sorry I am new to web development and Thank a Lot – User2403 Commented Jan 20, 2016 at 20:32
  • @User2403 That's correct, a link without an href does not get treated as a link jsfiddle/4n1rfwch/1 – Ruan Mendes Commented Jan 20, 2016 at 20:58
Add a ment  | 

2 Answers 2

Reset to default 2

I assume that the anchor attribute id or name contains information about the new URL.

Check out this example:

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

One way is to change the href attribute from the click handler

    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.?q=' + a.id);
    }
<a href="#" id="http://www.google." onclick="updateLink(this)" >Test</a>

发布评论

评论列表(0)

  1. 暂无评论