检查复选框是否被选中 jquery

发布于 2024-10-02 15:03:25 字数 476 浏览 0 评论 0原文

有谁知道为什么这不起作用。它总是打印“未选中”。

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

function msg(x)
{

if($(x).attr('checked')){
  alert('checked!!');
}
else{
  alert('unchecked');
}

}

</script>


</head>
<body>

<form>
<input type="checkbox" id="fname2" onClick="msg(this.id)" /><br/>

</form>

</body>
</html>

Does anyone know why this isn't working. It will always print 'unchecked'.

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

function msg(x)
{

if($(x).attr('checked')){
  alert('checked!!');
}
else{
  alert('unchecked');
}

}

</script>


</head>
<body>

<form>
<input type="checkbox" id="fname2" onClick="msg(this.id)" /><br/>

</form>

</body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

似狗非友 2024-10-09 15:03:25

您将 this.id 发送到该函数,然后将其包装在 $() 中。这是行不通的。您只需将 this 发送到 msg:onClick="msg(this)"

You are sending this.id to the function, then you are wrapping it in the $(). This does not work. You need just to send this to msg: onClick="msg(this)".

千里故人稀 2024-10-09 15:03:25

使用

function chkChecked(elmt) {
    if($(elmt).is(':checked')) {
        alert('checked!!');
    }
    else alert('unchecked');
}

Use

function chkChecked(elmt) {
    if($(elmt).is(':checked')) {
        alert('checked!!');
    }
    else alert('unchecked');
}
拍不死你 2024-10-09 15:03:25

你需要一个 # 来告诉 jQuery 你想要选择一个 id X 而不是一个元素 < a href="http://api.jquery.com/element-selector/" rel="nofollow">X。

if($('#'+x).attr('checked'))

或者,如果您将 onClick="msg(this.id)" 更改为 onClick="msg(this)" 您可以使用:

if($(x).attr('checked'))

You need a # to tell jQuery that you want to select an id X rather than an element X.

if($('#'+x).attr('checked'))

Or, if you change onClick="msg(this.id)" to onClick="msg(this)" you can use:

if($(x).attr('checked'))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文