【问题标题】:append a url typed into a input text field to an anchor then allow users to click on it and follow the url they typed将输入到输入文本字段中的 url 附加到锚点,然后允许用户单击它并按照他们输入的 url
【发布时间】:2013-09-19 08:03:43
【问题描述】:

我想要一个文本字段,人们可以在其中输入值。然后我想让一个 href 打开他们输入的网址。

与这个小提琴非常相似,但我希望 href 只是用户键入的输入值。

小提琴:

http://jsfiddle.net/BMDKr/

  <a href="/base/url" target="blank"  id="baseUrl">Link Text</a>
  <input type="text" id="appendUrl" />






$(function() {
$('#baseUrl').click( function() {
    window.location = $(this).attr('href') + '/' + $('#appendUrl').val();
    return false;
});
});

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    编辑:如果他们输入了外部 URL,要回答您的问题,您将使用此处找到的函数:Fastest way to detect external URLs?

    function isExternal(url) {
        var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/);
        if (typeof match[1] === "string" && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) return true;
        if (typeof match[2] === "string" && match[2].length > 0 && match[2].replace(new RegExp(":("+{"http:":80,"https:":443}[location.protocol]+")?$"), "") !== location.host) return true;
        return false;
    }
    

    结合当前的代码,这使得:

    function isExternal(url) {
        var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/);
        if (typeof match[1] === "string" && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) return true;
        if (typeof match[2] === "string" && match[2].length > 0 && match[2].replace(new RegExp(":("+{"http:":80,"https:":443}[location.protocol]+")?$"), "") !== location.host) return true;
        return false;
    }
    
    $(function () {
        // When the input field changes value
        $('#text').blur(function(){
    
            // Check if the link is external:
            if(isExternal($('#text').val())){
                // Set the attribute 'href' of the link to the value of the input field
                $('#link').attr('href', $('#text').val());
            }
            else
            {
                // Show an error if it's not external
                alert('Link is not external!');
            }
        });
    });
    
    <input type="text" id="text"> <a href="#" id="link">Link</a>
    

    小提琴:http://jsfiddle.net/BMDKr/6/

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多