【问题标题】:Splitting hash url to fill text fields in form拆分哈希 url 以填充表单中的文本字段
【发布时间】:2014-02-20 08:23:46
【问题描述】:

我有一个 javascript 函数,用于拆分参数的 url,然后使用找到的这些参数设置文本字段的值。它工作完美......一旦我刷新页面。如何在页面加载时填充文本字段?

$(function(){   
    var urlParams = {};
    (window.onload = function () {
        var match,
            pl     = /\+/g,
            search = /([^&=]+)=?([^&]*)/g,
            decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
            query  = window.location.search.substring(1);

        urlParams = {};
        while((match = search.exec(query)) !== null)
        urlParams[decode(match[1])] = decode(match[2]);
    })();
    window.onload=function(){
        var nm= urlParams['name'];
        var pn= urlParams['phone'];
        var em= urlParams['email'];
        document.getElementById('txtName').value=nm;
        document.getElementById('txtPhone').value=pn;
        document.getElementById('txtEmail').value=em;
    }
})

谁能帮帮我?

【问题讨论】:

    标签: javascript forms url hash


    【解决方案1】:

    首先,window.onload 太多了。当 DOM 准备好时,jQuery 的 $(function(){}) 将被触发,这对于您的情况应该足够了。但是我试图重现您的问题,但该功能对我有用。尝试删除 window.onloads 并告诉我它是否有帮助。也许准备一些jsFiddle也会很好。

    $(function(){
        var urlParams = {};
        (function () {
            var match,
                pl     = /\+/g,  // Regex for replacing addition symbol with a space
                search = /([^&=]+)=?([^&]*)/g,
                decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
                query  = window.location.search.substring(1);
    
            while((match = search.exec(query)) !== null)
            urlParams[decode(match[1])] = decode(match[2]);
        })();
    
        var nm= urlParams['name'];
        var pn= urlParams['phone'];
        var em= urlParams['email'];
        document.getElementById('txtName').innerText=nm;
        document.getElementById('txtPhone').innerText=pn;
        document.getElementById('txtEmail').innerText=em;
    
    })
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    相关资源
    最近更新 更多