jQuery:this.attr()不是函数吗? [英] jQuery: this.attr() not a function?
问题描述
我不确定我是否在正确的范围内使用此脚本,但是我有一个脚本基本上可以捕获链接点击并导致页面淡出,然后再转到链接的页面.但是,如果链接是JavaScript
I'm not quite sure if I'm not using this in the correct scope or what, but I have a script that basically captures a link click and causes the page to fade out before going to the linked page. However, if the link is a JavaScript onclick, the script fails.
这是我的代码:
<script type="text/javascript">
pageObj = {
init: function(){
$("body").fadeTo("slow", 1);
},
redirectPage: function(redirect){
window.location = redirect;
},
linkLoad: function(location){
$("body").fadeOut(1000, this.redirectPage(location));
}
};
$(document).ready(function() {
pageObj.init();
$("a").click(function(e){
e.preventDefault();
if (this.attr('onclick') !== undefined) {
eval(this.attr('onclick').val());
} else {
var location = this.href;
pageObj.linkLoad(location);
}
});
});
</script>
如您所见,我正在尝试检查链接是否具有 onclick 属性,然后调用 onclick 函数(如果存在).我该如何实现?
As you can see, I'm trying to do a check to see if the link has the onclick attribute, and then call the onclick function if it exists. How can I achieve this?
推荐答案
虽然Diodeus是正确的,但在使用attr()
之前,您需要将this
包装在jQuery集合中(这是jQuery集合的一种方法,而不是HTMLElement
),您也可以跳过attr()
.
While Diodeus is correct that you need to wrap this
in a jQuery collection before using attr()
(it's a method of a jQuery collection, not of an HTMLElement
), you can just as well skip attr()
.
$("a").click(function(e){
var location;
e.preventDefault();
if ($.isFunction(this.onclick)) {
this.onclick.call(this, e);
} else {
location = this.href;
pageObj.linkLoad(location);
}
});
请注意,我使用了属性(在加载HTML文档时,通常将属性预加载到属性中,而on_______
属性将被预加载为方法.还要注意,我使用了this.onclick.call()
而不是eval()
,设置了正确的this
用于onclick
方法,并确保对事件对象的访问作为参数.
Note that I used the property (when an HTML document loads, attributes are usually preloaded into properties, with on_______
attributes being preloaded as methods. Also note that I used this.onclick.call()
rather than eval()
, setting the correct this
for onclick
methods, and ensuring access to the event object as an argument.
这篇关于jQuery:this.attr()不是函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!