【问题标题】:Split Link and Insert into the Form拆分链接并插入表单
【发布时间】:2017-04-11 19:43:56
【问题描述】:

在我的网站上,我有一个 HTML 表单,如下所示:

<label>Name</lable>
<input name="username" id="username19" type="text" value="">

假设浏览器地址栏中的链接是:

https://sitename.com/consulting/order-plan/#ref/testing**

我想做以下事情:

从浏览器地址栏中选择 URL 并用“/”分隔。在这种情况下选择最后一个单词后,它是“testing”并将其插入到 ID 为“username19”的表单值中

你能帮我用 Javascript 或 jQuery 来做这件事吗?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

使用document.URL 获取当前网址并使用正则表达式获取最后一个单词

var url = document.URL;
var match = url.match(/([^/]*)$/);

console.log(url);
console.log(match);

document.getElementById("username19").value = match[1];
<label for="username19" >Name</lable>
<input name="username" id="username19" type="text" value="">

【讨论】:

  • 谢谢朋友,你很有帮助
【解决方案2】:

您可以使用window.location.pathname 从地址栏中获取当前路径,然后使用substr 将其拆分,最后使用lastIndexOf('/') 获取最后一部分,例如:

var current_path_name = window.location.pathname
console.log( current_path_name.substr(current_path_name.lastIndexOf('/') + 1) );

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    你可以试试-

    JavaScript :

    function ReplaceHash(){
        var url       = window.location.pathname;      /*URL without HASH*/
        var hash      = window.location.hash;          /*Only Hash URL*/
        var lastWord  = hash.split('/');
        lastWord[(lastWord.length)-1] = 'username19';  /*Put your text here*/
        hash          = lastWord.join('/');
        url           = url + hash;                    /*Your New URL*/
        return url;
    }
    
    var newUrl = ReplaceHash();
    console.log(newUrl);
    

    【讨论】:

      【解决方案4】:

      在加载输入元素后加载。但是你可以将它绑定到一个事件。

      $('input').load('input', function () {
        var str = window.location.pathname.split("/");         
        var res = str[str.length-1];
        document.getElementById("username19").setAttribute("value", res);
        console.log(res);
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <label>Name</lable>
      <input name="username" id="username19" type="text" value="">

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多