有人可以根据来自URL的参数值共享设置HTML文本(或在单选按钮或复选框旁边(上设置HTML文本的示例(最好在页面加载上(?我找到了许多方法来提取参数值和设置表单控件值的众多示例,但是没有将文本设置在按钮或无线电/复选框旁边的文本。用例是,我想为密码重置编辑的电子邮件或手机号码构建动态选择,并且我正在通过URL传递这些参数。
这是我对按钮类似的事情,但是我希望它们作为无线电按钮或复选框显示。
const hash = '?uname=greg&email=greg%40blah.com&phone=7777777';
const example = "http://example.com/" + hash;
function GetURLParameter(sParam) {
var sPageURL = example;
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
var phone = GetURLParameter('phone');
var email1 = GetURLParameter('email');
var email2 = decodeURIComponent(email1);
document.getElementById('myButton').innerHTML = phone;
document.getElementById('myButton2').innerHTML = email2;
<button id="myButton" type="button" value=""></button>
<button id="myButton2" type="button" value=""></button>
你有一个很好的开始。
我刚刚修改了您的代码以使用复选框而不是按钮。
对于每个值,生成了标签/无线电对并添加到文档主体中。
const hash = '?uname=greg&email=greg%40blah.com&phone=7777777';
const example = "http://example.com/" + hash;
function GetURLParameter(sParam) {
var sPageURL = example;
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return decodeURIComponent(sParameterName[1]);
}
}
}
// build array of values
var values = [
GetURLParameter('phone'),
GetURLParameter('email')
];
// add a label/radio-button for each value
for (var k in values) {
// create elements and text node
var label = document.createElement('label');
var radio = document.createElement('input');
var text = document.createTextNode(values[k]);
// set radio button properties
radio.type = "radio";
radio.name = "choose";
radio.value = values[k];
// if this is the first button, check it by default
if (k == 0) {
radio.checked = true;
}
// add the button and text node to the label
label.appendChild(radio);
label.appendChild(text);
// add the elements to the document body
document.body.appendChild(label);
};
label {
cursor: pointer;
}
label:not(:first-of-type) {
margin: 0 0 0 2em;
}
label input {
margin: 0 1em 0 0;
}