javascript - 如何提取此功能以不重复代码
问题描述
此代码检查复选框是否在站点上启用,如果它被禁用,那么它会禁用文本框。
函数disableTextBox()
是一个onclick
函数,$(function()
用于在刷新页面后检查复选框的行为,我没有使用它localstorage
,因为有时会使用不同的浏览器。
我怎样才能更好地编写此代码以不重复它?
如果选中复选框,则应启用文本框,如果未选中复选框,则应禁用任何输入的复选框。单击与此问题无关的保存按钮(即不同的功能)后,它会保存复选框,当用户返回页面时,它应该检查复选框是否被选中并调整文本字段。
任何想法如何写得更好或什么?
$(function()
{
var checkboxField = document.querySelector('#checkbox');
var textBox = document.querySelector('#textBox');
if (checkboxField.checked == true)
{
textBox.disabled = false;
}
else if (checkboxField.checked == false)
{
textBox.disabled = true;
}
});
function disableTextBox()
{
var checkboxField = document.querySelector('#checkbox');
var textBox = document.querySelector('#textBox');
if (checkboxField.checked == false)
{
textBox.disabled = true;
}
else if (checkboxField.checked == true)
{
textBox.disabled = false;
}
}
解决方案
调用你的disableTextBox()
函数,而不是if/else
你可以使用直接的评估boolean
结果checkboxField.checked
:
function disableTextBox() {
var checkboxField = document.querySelector('#checkbox');
var textBox = document.querySelector('#textBox');
textBox.disabled = !checkboxField.checked;
}
jQuery(function( $ ) {
// Do it on DOM ready
disableTextBox();
// and on button click
$('#btnDisableTextBox').on('click', disableTextBox);
// Other DOM ready functions here
});
推荐阅读
- python - 在视线上投射速度 - 已编辑
- javascript - 元素类型无效,使用 Flatlist 时
- multithreading - 在多个读者从 Rust 中的不同线程读取时写入
- javascript - 如何动态选择flex的属性来设置值?
- java - Android RecyclerView 项目点击不起作用 - MVVM
- scala - 如何从 spark scala 调用 db2 数据库中的存储过程
- python - 从数据框的代码中存储分类
- javascript - 循环 - 从数组中删除元素
- php - PHP搜索页面返回错误但搜索功能有效
- html - 如何在 html、css 中插入全屏大背景图片?