javascript - 根据 URL 参数选中复选框
问题描述
我正在尝试根据 URL 中的参数检查表单上的各种复选框。
URL 可能类似于以下内容:
https://development.mycompany.com/project/home.php?profile=profile1,profle2®ion=&rep=
如您所见,URL 中的“profile”参数有两个值(profile1、profile2)。
我有一个包含一系列复选框的表单,如下所示:
<input class="profileCheckbox" type="checkbox" id="PROFILE1CHECK" name="profileCheckbox" value="PROFILE1" />
<input class="profileCheckbox" type="checkbox" id="PROFILE2CHECK" name="profileCheckbox" value="PROFILE2" />
<input class="profileCheckbox" type="checkbox" id="PROFILE3CHECK" name="profileCheckbox" value="PROFILE3" />
// few more
使用 URL 参数,复选框 ID 的 PROFILE1CHECK 和 PROFILE2CHECK 应该被选中,而其他任何复选框都处于未选中状态。
我有这段代码可以抓取 URL 中的任何参数:
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
var profile = getUrlParameter('profile');
console.log(profile);
当我控制台配置文件变量时,我可以看到以下内容:
profile1,profile2
这就是我卡住的地方。
我不太确定如何检查 PROFILE1CHECK 和 PROFILE2CHECK 的 ID 复选框。
解决方案
var profile = getUrlParameter('profile');
$("#PROFILE1CHECK").attr("checked",profile.indexOf("profile1") !== -1);
推荐阅读
- scheme - 在 SICP 中推广素数对
- css - WooCommerce/CSS Span OnSale 背景颜色更改不起作用
- keycloak - Keycloak 在登录过程中添加动态用户会话注释
- jekyll - 根据文档,jekyll 不会将 site.url 转换为 http://localhost:4000
- qt - 避免 QML 错误:“这可能是一个信号处理程序,但没有目标信号与名称匹配。”
- node.js - VS Code - 从 node.js 项目生成 UML
- node.js - 使用 NodeJS 在 Cloud Functions 中编写 Cloud Monitoring 指标
- r - 如何制作一个 ggplot2 条形图,显示我的数据框列中的一和二的数量?
- c# - 与 c# 的 ASPX 连接
- python - 需要帮助理解 sorted(x for x in os.listdir(path)) 表达式