我正在尝试使用复选框来禁用和启用文本区域,同时切换框中的文本。我唯一的问题是我无法保留启用文本区域时所做的更改。文本区域最初被禁用并保存初始文本。启用文本区域后,文本变为可编辑。如果重新选中该复选框,更改就会消失,原始文本会重新出现 - 向后切换会删除更改(这不是我想要的)。我想来回切换文本,但不删除更改。我认为最好的方法是保留变量中的更改?我复制了下面的代码:
function toggleDisabled(_checked) {
document.getElementById('tjh').disabled = _checked ? true : false;
document.getElementById('tjh').value= "initial text";
}
<form>
<input type="checkbox" checked name="name1" onchange="toggleDisabled(this.checked)"/>
<textarea disabled name="name2" id="tjh">initial text</textarea>
</form>
最佳答案
您不需要在每次选中或取消选中复选框时从 textarea
读取值并将其存储到变量中。您也不需要(或应该)在 JavaScript 中设置 textarea
的初始值。在 HTML 中设置初始 textarea
内容,然后使用 javascript 将事件监听器附加到复选框,该复选框将根据是否选中从元素添加/删除 disabled
属性.
您可以在 HTML 元素上使用 onChange
属性,并像原来那样传递一个 javascript 函数,但在我看来,这样做不必要地将 HTML 和 Javascript 耦合在一起;使得更改和阅读变得更加困难。
<form>
<input type="checkbox" checked name="name1" id='name1' />
<textarea disabled name="name2" id="tjh">Initial text</textarea>
</form>
<script type='text/javascript'>
// Grab HTML elements by element's id
var txtBox = document.getElementById('tjh');
var checkBox = document.getElementById('name1');
var customText = 'initial text';
// Attach event listener to checkbox
checkBox.addEventListener('click', function(evt, el) {
// If checked, then save current textarea value and disable textarea
if (evt.target.checked) {
customText = txtBox.value;
txtBox.value = 'initial text';
txtBox.setAttribute('disabled', evt.target.checked);
}
// Otherwise restore text and reenable the textarea by removing disabled attribute from HTML element
else {
txtBox.value = customText ;
txtBox.removeAttribute('disabled');
}
}, false)
</script>
编辑:添加了 customText 变量以在禁用/启用复选框时存储/恢复 txtBox 值
关于javascript - 切换文本区域文本,但保留对文本的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983755/