我有一个简单的点击处理程序会提醒其链接的href
为:单独的事件处理程序的可重用性
<a id="link" href="http://www.google.com">Google</a>
$('a#link').on('click', function() {
alert($(this).attr('href'));
});
我怎么能分出功能(以及如何称呼它),这样它可以通过调用另一个点击处理?
function showHref() {
/* What to do here because $(this) won't resolve to <a> anymore. */
}
// I'd like a#another-link to be able to call that same function above.
<a id="another-link" href="http://www.microsoft.com">Microsoft</a>
$('a#another-link').on('click', /* How to call showHref? */);
谢谢。
它当然应该是'this.href',而不是'$(this).attr('href')',虽然;-) – Alnitak
@Alnitak:我通常不介意jQuery往返。 'this.className'适用于某些浏览器,而不适用于其他浏览器,'$(this).attr('class')'适用于所有。对我而言,jQuery的最大好处是不必处理不同的浏览器实现。在我看来,特定属性“href”在主流浏览器中的行为没有出现任何这种不一致的情况并不是一个非常有说服力的理由。 –