我有这样的代码:
$(document).ready(function() {
$("input[type='checkbox']").click();
$("input[type='checkbox']").change(function(e) {
if ( $("input[type='checkbox']").is(":checked") === true )
{
$("textarea").val("");
$("textarea").prop("placeholder", "");
$("textarea").prop("disabled", true);
}
else
{
$("textarea").prop("disabled", false);
$("textarea").prop("placeholder", "Write here");
}
}); //checkbox .change()
});
加载页面时,会发生单击事件,但不会启动更改事件。
这是正确的吗?还是我做错了什么?
谢谢。
单击复选框后设置事件。此外,您还应该在事件中使用"this":
$(document).ready(function() {
$("input[type='checkbox']").change(function(e) {
if ( $(this).is(":checked") === true )
{
$("textarea").val("");
$("textarea").prop("placeholder", "");
$("textarea").prop("disabled", true);
}
else
{
$("textarea").prop("disabled", false);
$("textarea").prop("placeholder", "Write here");
}
}); //checkbox .change()
$("input[type='checkbox']").click();
});
尝试更改:
if ( $("input[type='checkbox']").is(":checked") === true )
至
if (this.checked )
单击时,您尚未附加事件。在编写完事件定义后,编写您的$("input[type='checkbox']").click();
。尝试与相同的代码
$(document).ready(function() {
$("input[type='checkbox']").change(function(e) {
alert("Yes event triggered now");
if ( $(this).is(":checked") === true )
{
$("textarea").val("");
$("textarea").prop("placeholder", "");
$("textarea").prop("disabled", true);
}
else
{
$("textarea").prop("disabled", false);
$("textarea").prop("placeholder", "Write here");
}
}); //checkbox .change()
$("input[type='checkbox']").click();
});