我有一个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;
}
})
任何人都可以帮助我吗?
答案 0 :(得分:0)
首先,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;
})