我是JQuery的新手
我正在使用JQuery编写一个简单的数据验证。
以下是HTML部分:
<input type="text" id="testing">
这是JQuery部分:
$(document).ready(function(){
$("#testing").click(function(){
// doing something;
});
$("#testing").change(function(){
// doing something;
});
$("#testing").mouseover(function(){
// doing something;
});
});
$(“#testing”)在我的示例代码中重复了三次,是否可以简化这一点? 我不确定bind()是否可以帮助解决问题。
答案 0 :(得分:4)
您可以执行以下操作
$(document).ready(function() {
var testing = $('#testing');
testing.click(function() { });
testing.change(function() { });
testing.mouseover(function() { });
});
或(使用链):
$(document).ready(function() {
/* var testing = */ $('#testing') // the assignment is optional, but you can reuse the selector
.click(function() { })
.change(function() { })
.mouseover(function() { });
});
bind
你可以创建例如。自定义事件处理程序:
$(document).ready(function() {
var testing = $('#testing');
testing.bind('fill', function() { });
testing.trigger('fill');
});
阅读文档时,你也可以这样做:
$(document).ready(function() {
/* var testing = */ $('#testing') // the assignment is optional, but you can reuse the selector
.bind('click change mouseover', function() { });
});
或使用jquery 1.4:
$(document).ready(function() {
/* var testing = */ $('#testing') // the assignment is optional, but you can reuse the selector
.bind({
click: function() { },
change: function() { },
mouseover: function() { }
});
});
答案 1 :(得分:2)
jQuery是可链的。你也可以这样做,
$(document).ready(function(){
$("#testing").click(function(){
// doing somthing;
}).change(function(){
// doing somthing;
}).mouseover(function(){
// doing somthing;
});
});
或.bind()
$(document).ready(function(){
$("#testing").bind({
click : function(){
// doing somthing;
},
change : function(){
// doing somthing;
},
mouseover : function(){
// doing somthing;
}
});
});
如果您只有一个动作,则可以执行此操作,
$("#testing").bind('click change mouseover', function(){
// doing same thing on three events
})
答案 2 :(得分:1)
您可以在外部函数的开头设置var t = $("#testing");
一次(标识具有该id
的节点),然后调用t.click
,t.change
和{{ 1}}。
答案 3 :(得分:1)
#Testing不应该重复三次,因为#是一个id。你可以使用.Testing作为句号表示一个类。
<input type="text" id="Testing" class="myTesting"/>
'.myTesting'
我实际上更喜欢我的代码看起来像你的代码,因为它更容易准备。链接有时看起来和感觉很复杂,如果你错过了一个或者),它们很难被追踪。
但这纯粹是我的意见。
答案 4 :(得分:1)
链接方法会有更好的表现:
$("#testing").click(function(){
/* something */
}).change(function(){
/* something */
}).mouseover(function(){
/* something */
});
您可以将换行符放在任何位置:
$("#testing").click(function(){
/* something */
}) // don't put a semicolon here
.change(function(){
/* something */
}) // don't put a semicolon here either
.mouseover(function(){
/* something */
}); // put it here because you will not continue chaining.
Bind提供了额外的功能,但在这种情况下,它不是你要求的。