Reputation: 14155
inside html I want to render current url with # as addition inside a href element
Desired result would be for example: <a href="/Home/Contact#">MyLink</a>
so I tried with
<a href="javascript: getUrl();">My link</a>
<script>
function getUrl() {
return window.location.pathname + '#';
}
</script>
On page load this actually loads up this url from the script and as a result give me a blank page with /Home/Contact#
content, once again I just to render this url inside my a href element, not to execute that link on page load.
Upvotes: 0
Views: 749
Reputation: 1074959
Identify the links with some kind of common marker (such as a class or a data-*
attribute), for instance:
<a class="the-common-class">My link</a>
...then once you have the base path (or just at the end of the HTML, just prior to the closing </body>
tag) update their href
attribute:
$(".the-common-class").href(window.location.pathname + "#");
If they should have different hash fragments, the data-*
attribute would probably work better:
<a data-hash="something">My link</a>
then:
$("a[data-hash]").href(function() {
return window.location.pathname + "#" + this.getAttribute("data-hash");
});
or if you want more jQuery:
$("a[data-hash]").href(function() {
return window.location.pathname + "#" + $(this).attr("data-hash");
});
(Note: Don't use .data("hash")
, that's not what it's for.)
Upvotes: 2
Reputation: 67525
You can use :
function getUrl() {
$(this).attr('href', window.location.pathname + '#');
}
Upvotes: 0