[英]$(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;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.