我如何处理 Jquery 中的选中事件和单击事件
假设我有一个表单并加载该表单,我有 2 个单选按钮说“是”或“否” 当我们选择任一单选按钮时,我要执行一组操作。假设我们选择“是”
//Onload of Form
if(("#yes:checked")){
$("#table").show();
$("#div1").show();
$("#div2").show();
alert("Checkedd on Load");
}
//单击
$("#yes").bind('click',function(){
$("#table").show();
$("#div1").show();
$("#div2").show();
alert("Checked by Click"); });
});
我正在为两组相似的事件编写相同的重复代码行。是否有任何方法可以组合“已检查”和“点击”事件 假设我这样做,那么“已检查”不会被调用,直到“已单击”为止?还有其他方法可以做到这一点吗?
$("#yes").bind('click',function(){
if(("#yes:checked")){
$("#table").show();
$("#div1").show();
$("#div2").show();
alert("Checked by Click");
}
});
});
Say I have a form and onload of that form I have 2 radio buttons say "yes" or "no "
I have set of action to perform when we select either one radio button .Say if we select "yes "
//Onload of Form
if(("#yes:checked")){
$("#table").show();
$("#div1").show();
$("#div2").show();
alert("Checkedd on Load");
}
//for click
$("#yes").bind('click',function(){
$("#table").show();
$("#div1").show();
$("#div2").show();
alert("Checked by Click"); });
});
Iam Writing the same repeated lines of code for two similar set of events .Is There anyway to combine the "Checked" and "Clicked" events
Say if i do inthis way than "Checked" doesnot get called untill "Clicked"?Is there any other way to do it.
$("#yes").bind('click',function(){
if(("#yes:checked")){
$("#table").show();
$("#div1").show();
$("#div2").show();
alert("Checked by Click");
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实现它的方法之一是创建一个函数来执行所有常见操作,然后在事件发生时调用该函数。
和
One of the ways to achieve it is to create a function which will do all the common operations, and then call this function when event occurs.
and
您可以使用
.bind()
组合多个事件,例如您可以查找
事件对象
来确定实际触发了哪个事件如果您想为这些事件执行完全相同的代码,您可以跳过第一个
break
语句。无论如何,在您的特定情况下,我相信您只需要change
事件。在事件处理程序中,您只需检查该元素当前是否已选中:要在加载站点时执行事件处理程序代码,您可以
.trigger()
它就像You can combine multiple events with
.bind()
likeYou can lookup the
event object
to determine which event actually was triggeredIf you want to execute the exact same code for those events, you can just skip the first
break
statement. Anyway, in your particular case I believe you only need thechange
event. In your event handler you just check if the element is currently checked or not:To execute the eventhandlers code when loading your site, you can
.trigger()
it like这样,您定义一次代码并多次调用它:)
您甚至可以将警报写入函数并为其提供所需的字符串:
并调用类似
processCheck("Checked on Load");
希望有帮助:)
That way you define the code once and call it multiple times :)
You could even write the alert into the function and give it the string desired:
And call something like
processCheck("Checked on Load");
Hope that helps :)