嗨我有一些jquery复选框选中的问题。我想在选中复选框时执行任务。我的代码是这样的jquery chekbox选择
$(document).ready(function() {
if ($('#chxGetText').is(':checked')) {
alert("OK");
}
});
<input id="chxGetText" type="checkbox" />
但是,当我检查复选框时没有任何事情发生。有任何想法吗?
嗨我有一些jquery复选框选中的问题。我想在选中复选框时执行任务。我的代码是这样的jquery chekbox选择
$(document).ready(function() {
if ($('#chxGetText').is(':checked')) {
alert("OK");
}
});
<input id="chxGetText" type="checkbox" />
但是,当我检查复选框时没有任何事情发生。有任何想法吗?
:checked
只是一个选择,它不绑定任何事件侦听器。做这样的事情:
$(document).ready(function() {
$('#chxGetText').change(function (e) {
if($(this).is(':checked')) {
alert('Checked');
}
else {
alert('Unchecked');
}
});
});
<input id="chxGetText" type="checkbox" />
您需要将事件侦听器绑定到复选框的更改事件。现在,您只会检查是否在页面加载时检查复选框,即一次。
$(function() {
$('#chxGetText').change(function() {
if ($(this).is(':checked')) {
alert('OK');
} else {
alert('Not OK');
};
}).trigger('change'); // trigger it on page load as well
});
请注意,你应该触发页面加载时为好,如果用户选中复选框(因此.trigger('change')
在我的代码)后刷新页面。
大码马蒂亚斯代码,我将使用这个其他网页,我得到 – 2010-04-15 07:13:51
你没有分配一个事件的元素,试试这个:
$(document).ready(function() {
$('#chxGetText').click(function(){
if ($(this).is(':checked')) {
alert("OK");
}
});
});
这将工作过程中,对.trigger fosho,但它可能是一个好主意执行此检查页面加载以及:http://stackoverflow.com/questions/2643266/2643275#2643275 – 2010-04-15 07:04:20
感谢您的工作很好 – 2010-04-15 07:06:57
@ Dejan.S:欢迎您....... :) – Sarfraz 2010-04-15 07:33:35
您需要为复选框的onclick
事件分配事件处理程序。当前的代码只运行一次,当文档被加载时,并且在此之后不会对任何状态更改做出反应。
<input id="chxGetText" type="checkbox" />
function checkState(node) {
if (node.checked) {
alert("OK");
}
}
$(document).ready(function() {
$('#chxGetText').click(function() {
// Bind checkState to click event
checkState(this);
}).each(function() {
// Initial check on load
checkState(this);
});
});
使用jQuery和没有突兀的JavaScript? – Sarfraz 2010-04-15 07:00:51
你说得对,我应该(或者至少可以)完全在这个解决方案中跳过jquery。我只是试图说明为什么最初的解决方案没有按预期工作。 – 2010-04-15 07:07:27
错误,不 - 你应该使用不引人注目的JavaScript。 jQuery与否。 – 2010-04-15 07:26:15
您可以像使用
jQuery("#chxGetText").click(function() {
if ($(this).is(':checked')) {
alert("#chxGetText is checked");
}
else {
alert("#chxGetText is unchecked");
}
});
你正在使用'function(e)',但你没有使用'e'。为什么不省略它? – 2010-04-15 07:03:31
我用这个删除了Mathias Bynens的评论。不是那个代码烦扰了,因为它没有被使用。谢谢 – 2010-04-15 07:13:04
@Mathias:我可能会在我自己的代码中,除非我想检查或调用事件对象的方法。只是想表明事件处理程序传递了一个事件对象。 – PatrikAkerstrand 2010-04-15 07:36:49