jQuery:this.attr() 不是一个函数?
我不太确定我是否没有在正确的范围内使用它或什么,但我有一个脚本,它基本上捕获链接点击并导致页面在转到链接页面之前淡出。但是,如果链接是 JavaScript onclick,则脚本会失败。
这是我的代码:
<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 函数(如果存在)。我怎样才能实现这个目标?
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.
Here's my code:
<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>
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用:
$(this).attr
而不是this.attr
这会强制它进入 jQuery 的上下文。
Use:
$(this).attr
instead ofthis.attr
This forces it into the context of jQuery.
虽然 Diodeus 是正确的,但您需要在使用
attr()
之前将this
包装在 jQuery 集合中(它是 jQuery 集合的方法,而不是HTMLElement< /code>),您也可以跳过
attr()
。请注意,我使用了属性(当加载 HTML 文档时,属性通常会预加载到属性中,
on_______
属性会作为方法预加载。另请注意,我使用了this.onclick.call()
而不是eval()
,为onclick
方法设置正确的this
,并确保将事件对象作为参数进行访问。While Diodeus is correct that you need to wrap
this
in a jQuery collection before usingattr()
(it's a method of a jQuery collection, not of anHTMLElement
), you can just as well skipattr()
.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 usedthis.onclick.call()
rather thaneval()
, setting the correctthis
foronclick
methods, and ensuring access to the event object as an argument.