我试图将文本框设置为“只读”,添加一个类,然后在选中复选框时将文本放入文本框中。此外,我还尝试从文本框中删除“只读”属性,添加一个类,并删除文本框中的文本。
我有
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
此代码对我不起作用。
谢谢
菲利普
<小时/>谢谢大家的解答。
根据您的评论和回答,我更改了代码,但仍然无法正常工作。
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').prop('readonly', true);
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text('disabled');
}
else {
$('#TextBoxSectionCode').prop('readonly', false);
$('#TextBoxSectionCode').removeClass('disabled').addClass('enabled');
$('#TextBoxSectionCode').text('');
}
});
我使用 chrome 浏览器来运行此代码,并使用 chrome 中的开发人员工具并在上面的代码处放置一个断点,以查看 jquery 中发生了什么。但是,当我单击复选框进行选中/取消选中时,没有任何反应。
最佳答案
document.getElementById('TextBoxSectionName').val
这是错误的。你确实应该缓存你的 jQuery 对象,这样它就不会一遍又一遍地浏览 DOM。然后你混合原生JS,.val不是一个DOM属性或方法,也不是一个jQuery属性,它应该是 DOM 对象的 .value
或 .val()
一个 jQuery 对象。
@Archy Wilhes 的强制性解释:
"Just to clarify; when @SterlingArcher says caching the jQuery object, she/he means doing something like var obj = $('#TextBoxSectionCode') then calling the functions using the variable like this: obj.attr(...); obj.addClass(...). Every time you do a $(something) you are calling a function in jQuery that looks for the DOM."
关于javascript - 复选框和点击事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29478318/