$(this).attr("href")返回未定义
$(this).attr("href") return undefined
我正在尝试使用bootbox与Twitter Bootsrap。
在下面的代码中,当我使用this.attr('href');
并得到TypeError: this.attr is not a function
时。
当我改变到$(this).attr('href');
我得到Undefined
。
<a class="alert" href="list_users.php?id=123">Delete user</a>
<script src="bootbox.min.js"></script>
<script>
$(document).on("click", ".alert", function(e) {
e.preventDefault();
bootbox.confirm("Are you sure?", function(result) {
if (result) {
document.location.href = this.attr('href'); // doesn't work
document.location.href = $(this).attr('href'); // Undefined
}
});
});
</script>
任何想法?
这不再是你的jQuery事件回调函数,但bootbox回调…尝试$.proxy
绑定上下文:
$(document).on("click", ".alert", function(e) {
e.preventDefault();
bootbox.confirm("Are you sure?", $.proxy(function(result) {
if (result) {
document.location.href = this.href;
}
}, this));
});
问题是this
或$(this)
不再指向链接,而是bootbox
-回调。这可以通过存储$(this)
所指向的变量来修复。注意,如果多次使用同一个对象,这也被认为是良好的实践。
$(document).on("click", ".alert", function(e) {
e.preventDefault();
var obj = this;
bootbox.confirm("Are you sure?", function(result) {
if (result) {
document.location.href = obj.href;
}
});
相关文章:
- "日期“;AJAX请求返回的类型值未定义
- "这个“;正在返回未定义的
- 我对“;返回true"嵌套函数内部;t工作
- "navigator.msLaunchUri”;在IE Edge中,始终返回成功
- window.safari.pushNotification.requestPermission总是返回"拒绝
- Typeahead.js-特殊字符返回为“”&#230"等
- 如何在ajax中返回文本文件值Asynchronous"Synchronous正在被弃用”;
- 奇怪的行为angularjs返回"类型错误:无法分配给只读属性"
- 当我运行返回()时"":""Javascript中的语法,只有当我将文件保存为PHP
- 为什么"document.styleSheets”;每次刷新3到5次浏览器后返回空值
- 为什么element.getAttribute(“style”)忽略冒号“”之后的所有内容:"性格仅返回部分值
- 为什么var c=“;a“||"b”;返回c=“;a“;并且var c=“0”;a“&&"
- 将socket.io/socket.io.js加载到html头中返回"ReferenceError:io未定义
- "闭合的“;属性异常返回“;window.open”;在JavaScript&歌剧
- 带错误的Onsen UI导航:您不能提供no"ons页”;元素到“;ons导航器”;当返回第一页时
- document.getElementsByClassName().inerHTML总是返回"未定义”;
- "返回函数外的语句“-JavaScript错误
- Dojo.request.post-返回的promise说"拒绝”;,但服务器似乎已经接受了请求
- 为什么d3.json会返回"空”;
- Firefox getComputedStyle返回"自动”;