我有一个输入字段,需要用URL查询字符串填充,页面名称为" track"。
输入代码:
<div class="page-width">
<h1 class="small--text-center">{{ page.title }}</h1>
<input type="text" id="trackid" name="tracking" placeholder="Tracking ID">
<button type="button" onClick="changeChannel();">Locate My Item</button>
网址是:
mysite.com/pages/track?trackid=123
我该怎么做?
答案 0 :(得分:0)
如果我理解你的意思,你的代码应该是这样的:
<div class="page-width">
<h1 class="small--text-center">{{ page.title }}</h1>
<input type="text" id="trackid" name="tracking" placeholder="Tracking ID">
<button type="button" onClick="changeChannel();">Locate My Item</button>
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var name = 'trackid'; // if your url is mysite.com/pages/track?trackid=123
var url = window.location.href;
document.getElementById("trackid").value = getParameterByName(name, url);
</script>
此代码将使用url查询字符串中的trackId值初始化输入字段。