简体   繁体   English

如何在HTML链接中使用JavaScript变量

[英]How to use JavaScript variable in an HTML link

The website that I am working on has a <base> tag point to a different URL than the one that the website has. 我正在工作的网站的<base>标记指向与该网站不同的URL。 What I would like to do is get around the <base> tag by using the trueURL bellow to find the url of the webpage, because i need it to construct some internal anchors, because i need the actual url of the website so the internal anchors work correctly. 我想做的是通过使用trueURL波纹管找到网页的URL,从而绕过<base>标记,因为我需要它来构造一些内部锚点,因为我需要网站的实际URL,因此内部锚点正常工作。

The issue that im having is that i don't know how i should use the url that i store in my trueURL variable. 我有的问题是我不知道如何使用我存储在trueURL变量中的url。 Is it possible to use it and then add extra extensions to the url to get it to point to my anchors? 是否可以使用它,然后在URL中添加额外的扩展名使其指向我的锚点? Below is a rough example of what I would like to be able to do 以下是我想做的一个粗糙的例子

var trueURL = window.location.href;

    <html>

    <ol>
        <li>
            <a href= [trueURL] + "#link1">Link1</a>
        </li>

        <li>
            <a href= [trueURL] + "#link2">Link2</a>
        </li>

        <li>
            <a href= [trueURL] + "#link3">Link2</a>
        </li>
    </ol>

    </html>

Therefore in the end i would like to have a link that looks like trueURL#link3. 因此,最后我想拥有一个看起来像trueURL#link3的链接。

Thanks in advance, 提前致谢,

:D :D :D:D

I am working on the assumption that your real case is more complex than your example. 我正在假设您的实际案例比您的示例更为复杂。 If it isn't, then review the other answers, which may be more appropriate for what you need to do. 如果不是,请查看其他答案,这可能更适合您的需要。

What this will do is... 这将是...

  1. Run on the window load event a function that will... window加载事件上运行一个函数,该函数将...
  2. Find every element in the DOM that is an A tag, and... 查找DOM中每个是A标签的元素,然后...
  3. Loop through those found A tags and check if the element has an enhance class, and if so... 遍历找到的A标记,并检查该元素是否具有enhance类,如果是,则...
  4. Split the href at the # to get the current a element's hash value, which we will... 拆分href#来获取当前a元素的hash值,我们将...
  5. Combine it with the following: 结合以下内容:

     '//' + location.host + location.pathname; 

    Giving us the current page's URL without a hash or query string. 提供当前页面的URL,不带hash或查询字符串。 If you want the query string (what's after the ? in a URL), add location.search : 如果您查询字符串(URL中的?后面),请添加location.search

     '//' + location.host + location.pathname + location.search; 

Note, the // part is protocol relative, so it will use whatever the base href 's protocol is, eg, http or https . 注意, //部分是相对于协议的,因此它将使用base href的协议是什么,例如httphttps You may want to specify that, however. 但是,您可能需要指定。

Markup 标记

Note the class attribute, which we will use to identify which a tags to manipulate. 注意class属性,我们将使用它来识别要操作a标签。

<ol>
    <li>
        <a href="#link1">Link 1</a> - 
        No enhance class, should be subject to <strong>BASE HREF</strong>: 
        <strong class="p">&raquo; http://example.com#link1</strong>
    </li>
    <li>
        <a href="#link2" class="enhance">Link 2</a> - 
        Has enhance class, should be:
        <strong class="p">&raquo; http://fiddle.jshell.net/_display/#link2</strong>
    </li>
    <li>
        <a href="#link3" class="enhance">Link 3</a> - 
        Has enhance class, should be:
        <strong class="p">&raquo; http://fiddle.jshell.net/_display/#link3</strong>
    </li>
    <li>
        <a href="#link3" class="enhance">Link 4</a> - 
        Has enhance class, should be:
        <strong class="p">&raquo; http://fiddle.jshell.net/_display/#link4</strong>
    </li>
</ol>​

Javascript 使用Javascript

//--
// window.onload is not preferred, window.addEventListener
// should be used. Except that only IE9 supports it, and
// IE8 and lower do not support it, and uses window.attachEvent
// instead, which you can test for. 
//
// I'm using window.onload here simply as a shortcut method and
// for clarity. This can also go in a script tag at the bottom
// of the body tag, in which case you can remove window.onload
// and use a self-calling anonymous function like:
//
//     (function updateLinks(){... all the same as below ...})();
//
// This will ensure you are out of the global variable scope.
//--
window.onload = function updateLinks() {
    //--
    // Modern browsers can use document.getElementsByClassName
    // or you can use a shiv script to add it to browsers that 
    // don't. I'll do it the "manual" way here, and this works
    // cross-browser. The downside is that it will interate 
    // through every A tag on the page, looking for the "small"
    // few that have the el.className we're looking for here.
    //--
    var els = document.getElementsByTagName("a"),
        l = els.length,
        trueURL = '//' + location.host + pathname,
        i, el, hash;

    for (i = 0; i < l; i++) {
        el = els[i];

        if (el.className.indexOf("enhance") != -1) {
            hash = el.href.split('#');
            el.href = trueURL + "#" + hash[1];
        }
    }
};

http://jsfiddle.net/userdude/unnH8/ http://jsfiddle.net/userdude/unnH8/

Mouseover the links to see the current setting. 将鼠标悬停在链接上以查看当前设置。 As always, thoroughly test with real markup in multiple browsers . 与往常一样, 在多个浏览器中使用真实标记进行全面测试

If you are serious about trueURL = window.location.href then you are working WAY too hard. 如果您认真对待trueURL = window.location.href那么您的工作方式太辛苦了。

Just make the link #link1 - it automatically will be relative to the current href. 只需创建链接#link1它就会自动相对于当前href。

If that was just an example, you may be interested in the: 如果仅是示例,您可能会对以下内容感兴趣:

<BASE href="...">

tag. 标签。 This will let you change the relative href for all links in the page at once. 这样您就可以一次更改页面中所有链接的相对href。

And you can do it with javascript by getting each <A...> DOM element and modifying the href property. 你可以通过获取每个JavaScript的做<A...> DOM元素和修改href属性。

First, if you're not using base yet or are but can switch away from using it, please read: 首先,如果您尚未使用base ,或者可以但不再使用base ,请阅读:

Is it recommended to use the <base> html tag? 是否建议使用<base> html标签?

Which will give you many good reasons to think twice. 这将使您有很多理由三思。 Moral of the story: It's usually a bad idea to use base . 故事的寓意:使用base通常不是一个好主意。 There are good reasons, and it is useful; 有充分的理由,而且很有用; I have used it to great delight many times when working with designers to have local copies of the markup that I can work with but still maintain connections back into the site's assets. 当与设计师合作获得可以使用的标记的本地副本,但仍保持与站点资产的连接时,我曾多次使它感到高兴。 But for production sites, it's too clever by half. 但是对于生产站点来说,它太聪明了。

Also, this answer was originally written for a different question that was an exact duplicate, so I'm posting this here, although there's an answer that's very similar to it already. 另外,这个答案最初是为另一个完全相同的问题而写的,因此尽管这里的答案已经非常相似,但我还是将其张贴在这里。


Do you have control over the markup or can you use a selector to get only the elements you want to effect? 您可以控制标记,还是可以使用选择器仅获取要影响的元素? You could: 你可以:

HTML (Note the class truelink .) HTML (注意类truelink 。)

<ol>
    <li>
        <a href="#link1" class="truelink">True Link1</a>
    </li>
    <li>
        <a href="#link2" class="truelink">True Link2</a>
    </li>
    <li>
        <a href="#link3" class="truelink">True Link3</a>
    </li>
</ol>

Javascript 使用Javascript

​window.addEventListener('load', function links(){
    var base = document.getElementsByTagName('base')[0],
        links = document.getElementsByClassName('truelink'),
        l = links.length,
        uri = 'http://www.host.tld/path?query=test';

    console.log('Base:', base, ', True Links:', links);

    console.log('Modifying links in five seconds...');

    setTimeout(function go(){
        console.log('Modifying links now...');

        while (l--){
            links[l].href = links[l].href.replace(base.href, uri);
        }

        console.log('Base: ', base, 'True Links: ', links);
    }, 5000);
});​

http://jsfiddle.net/M5Hdk/ http://jsfiddle.net/M5Hdk/

Keep in mind that this technique demonstrates using document.getElementsByClassName , which is not supported by IE until version 9. If you have to support lower versions than IE9, see Jeremy J Starcher's answer for a less "efficient" but better supported method. 请记住,此技术演示了如何使用document.getElementsByClassName ,直到版本9 IE才支持IE。如果必须支持比IE9更低的版本,请参见Jeremy J Starcher的答案,以获取一种“效率较低”但受支持更好的方法。 There's also document.querySelectorAll , which is supported by IE8 and above and all other major browsers. 还有document.querySelectorAll ,IE8和更高版本以及所有其他主要浏览器都支持它。 If you only need to support IE8, I would suggest using this to select your links over the method Jeremy demonstrates. 如果您只需要支持IE8,建议您使用它来选择Jeremy演示的方法上的链接。

I also delay the change for five seconds so you can see it work. 我还将更改延迟了五秒钟,以便您可以看到它的工作。 Obviously, this won't be necessary for you (most likely). 显然,这对于您(很有可能)不是必需的。

The only thing I'm not sure about right now is whether or not my .replace() will always find the base.href to replace in all browsers, so it may be better to detect the presence of a relative url before doing a replace, so you can do whatever else appropriately. 我现在不确定的唯一事情是我的.replace()是否将始终在所有浏览器中找到要替换的base.href ,因此最好在进行替换之前检测相对URL的存在,因此您可以做其他适当的事情。 For some related background on this possible "issue", see my question that deals with how browsers handle href attributes differently in the DOM: 有关此可能的“问题”的一些相关背景,请参阅我的问题,该问题涉及浏览器如何在DOM中不同地处理href属性:

Method for selecting elements in Sizzle using fully-qualified URLs 使用完全限定的URL在Sizzle中选择元素的方法

Also, this will perhaps work most seamlessly if it falls in an inline script tag right after the content, or at the end of body tag, in which case you will want to remove the window.addEventListener part and replace with a self-executing function. 此外,如果落在一个内联,这将可能是工作的大部分无缝script标签内容之后,或者在结束body标记,在这种情况下,你将要删除的window.addEventListener一部分,并与自动执行的功能替换。

Their are other options, all are probably a little more problematic: 他们是其他选择,所有选择都可能有更多问题:

  • Blow away the base tag altogether. 完全吹走base标签。 If you do this, though, you'll first want to check if you need to manually insert the base.href content into the links, otherwise I'm sure things can break or become brittle. 但是,如果执行此操作,则首先要检查是否需要手动将base.href内容插入链接中,否则我确定事情会破裂或变脆。
  • Add an event listener to the a links you want to use your true link and manipulate it that way onclick , just don't forget to return false at the end of the click handler function, so the browser doesn't follow the link. 将事件侦听器添加到要使用真实链接的a链接中,并以onclick方式进行操作,只是不要忘记在click handler函数的结尾处return false ,因此浏览器不会遵循该链接。 This is probably the most seamless method, but is probably not best for all situations. 这可能是最无缝的方法,但可能并非在所有情况下都最佳。
  • Probably others. 可能是其他人。

Be sure to test with real world markup. 确保使用真实世界的标记进行测试。 base is a mildly quirky tool, so manhandling it may lead to unusual side effects. base是一个有点古怪的工具,因此处理它可能会导致异常的副作用。 You were warned . 你被警告了

I would have done it this way 我会这样做

HTML HTML

<ol>
    <li>
        <a class="build">Link1</a>
    </li>

    <li>
        <a class="build">Link2</a>
    </li>

    <li>
        <a class="build">Link2</a>
    </li>
</ol>​

Javascript/Jquery 使用Javascript / jQuery的

$(function(){
    var trueURL = window.location.href;
    var i = 1;
    $('a.build').each(function(){
        $(this).attr('href', trueURL + '#link' + i);
        i = i+1;
    });
});

Example of working code Here 这里的工作代码示例

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

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