首页 > 解决方案 > 如何提取此功能以不重复代码

问题描述

此代码检查复选框是否在站点上启用,如果它被禁用,那么它会禁用文本框。

函数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;
}
}

标签: javascript

解决方案


调用你的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
});

推荐阅读