如何使用 javascript 在文本字段中输入文本

How to input text into text field with javascript

我在 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 填写文本字段?

您可以只设置输入字段的值 (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>

您可以尝试 DOM id 选择器:

<input class="tnp-email" type="email" name="ne" id="yourId" required>

document.getElementById("yourId").innerHTML = "Your text";

您可以像这样使用 DOM class 名称选择器:

 var x = document.getElementsByClassName("tnp-email");
 x[0].value = "Your value";