javascript - 复选框和点击事件处理

标签 javascript c# jquery

我试图将文本框设置为“只读”,添加一个类,然后在选中复选框时将文本放入文本框中。此外,我还尝试从文本框中删除“只读”属性,添加一个类,并删除文本框中的文本。

我有

$('#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/

相关文章:

javascript - 使用 Javascript 关闭侧边栏

c# - Tasks 和 WaitAll 的递归

C# - 两个日期之间的差异?

javascript - 最近表的最近表

javascript - 360度PNG序列拖动

javascript - 通过更改时选择的值更改输入值

javascript - 简单的jquery代码优化

javascript - Web 应用程序中具有自动淡入/淡出功能的 iPhone 样式滚动条

javascript - JQuery 回调函数流程

c# - MSI 为安装人员提出问题