[英]What is the equivalent jQuery code to the following JavaScript which saves off onclick events?
So in JavaScript I can do the following: 所以在JavaScript中我可以做到以下几点:
var someObj = document.getElementById("foo");
var fooClick = foo.onclick;
var someOtherObj = document.getElementById("bar");
someOtherObj.onclick = fooClick;
I'm wondering, what is the jQuery equivalent to the code above? 我想知道,jQuery等同于上面的代码是什么?
Thanks! 谢谢!
Is it really required that you get the event handler from another object? 是否真的需要从另一个对象获取事件处理程序? That doesn't seem like a great idea to me.
这对我来说似乎不是一个好主意。 A better way would be to define the handler, and assign it to both objects.
更好的方法是定义处理程序,并将其分配给两个对象。
var clickHandler = function(e) { alert('click!'); };
$('#foo,#bar').click(clickHandler);
var someObj = $("#foo").get(0);
var fooClick = someObj.onclick;
$("#bar").click(fooClick);
or if you want this in one line: 或者如果你想在一行中:
$("#bar").click($("#foo").get(0).onclick);
Just adding to Daniel Schaffer's answer (+1'd), you can also inline your click 'handler' definition, for example: 只需添加Daniel Schaffer的答案(+ 1'd),您还可以内联点击'处理程序'定义,例如:
$("#foo, #bar").click( function() {
alert( this.id + ' was clicked.' );
} );
The behaviour should be the same, but depending on your coding style taste, you may prefer this (I do). 行为应该是相同的,但根据你的编码风格品味,你可能更喜欢这个(我愿意)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.