我在wordpress网站上有一个带有文本字段的表单,用于填写电子邮件地址,如下所示:
<div class="tnp-field tnp-field-email"><label>Email</label><input class="tnp-email" type="email" name="ne" required></div>
我可以从get参数(www.domain.com/?email=test@mail.com)获取电子邮件地址,如下所示:
<script type='text/javascript'>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if(window.location.href.indexOf(parameter) > -1){
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
var emailtxt = getUrlParam('email','');
如何用 emailtxt 填充文本字段?
答案 0 :(得分:1)
您只需设置输入字段(HTMLInputElement.value = "value"
)的值即可。
document.querySelector("input[name=ne]").value = getUrlParam('email','');
<div class="tnp-field tnp-field-email"><label>Email</label><input class="tnp-email" type="email" name="ne" required></div>
<script type='text/javascript'>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if(window.location.href.indexOf(parameter) > -1){
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
var emailtxt = getUrlParam('email','');
console.log(emailtxt);
document.querySelector('input[name=ne]').value = emailtxt;
</script>
答案 1 :(得分:1)
您可以尝试DOM ID选择器:
<input class="tnp-email" type="email" name="ne" id="yourId" required>
document.getElementById("yourId").innerHTML = "Your text";
答案 2 :(得分:1)
您可以像这样使用DOM类名称选择器:
var x = document.getElementsByClassName("tnp-email");
x[0].value = "Your value";