I am trying to use bootbox with Twitter Bootsrap.
In the code below when I use this.attr('href');
and I get TypeError: this.attr is not a function
.
When I change to $(this).attr('href');
i get 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>
Any idea?
I am trying to use bootbox with Twitter Bootsrap.
In the code below when I use this.attr('href');
and I get TypeError: this.attr is not a function
.
When I change to $(this).attr('href');
i get 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>
Any idea?
Share Improve this question edited Jun 10, 2013 at 22:08 Odys 9,10011 gold badges75 silver badges116 bronze badges asked Jun 10, 2013 at 21:57 OualidOualid 4031 gold badge9 silver badges23 bronze badges 1- 1 jQuery !== Javascript – PlantTheIdea Commented Jun 10, 2013 at 21:58
2 Answers
Reset to default 7That's not your jQuery event callback function anymore, but the bootbox callback... try $.proxy
to bind the context:
$(document).on("click", ".alert", function(e) {
e.preventDefault();
bootbox.confirm("Are you sure?", $.proxy(function(result) {
if (result) {
document.location.href = this.href;
}
}, this));
});
The problem is that this
or $(this)
no longer is pointing to the link, but the bootbox
-callback. This can fixed by storing the variable that $(this)
is pointing to. Note that this is also considered good practice if you are using the same object multiple times.
$(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;
}
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744787447a4593713.html
评论列表(0条)