Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
I ran into a very vague error while doing some simple jQuery DOM manipulation.
The line that triggered the error is the following:
$(this).closest('tr').remove();
The error, as stated in the title, is:
Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
in file: jquery-1.6.2.js
.
I have already tried with jQuery 1.6.3 and jQuery 1.5.1, but nothing changed. I still keep getting the error.
The line above is bound to a button which, when clicked, submits an AJAX POST request, then when successful, it removes its own <tr>
. I have already tried another way by doing:
$(this).parent().parent().remove()
but to my surprise, this did nothing.
I'm using Chrome, in case it matters, but I get the same error in FF.
EDIT:
This is my code:
$(".remove").live('c开发者_如何转开发lick', function(e) {
var str = $(this).attr('id').match(/\[(.*?)\]\[(.*?)\]/);
var type = str[1];
var id = str[2];
// IF I PUT THE remove() HERE, IT WORKS.
$.ajax({
type: 'POST',
url: '/admin/ajax_remove_event_detail',
data: {type: type, id: id},
success:function(res) {
if(res)
{
$(this).closest('tr').remove();
// this gives me an error
}
else
{
// error handling
}
}
});
e.preventDefault();
});
If I put the remove() outside of the if somewhere, it works. Why won't it work when it's inside the ajax call/if? Makes no sense to me? :(
Any help here? Thanks in advance.
I don't know what you expect the value of this
to be in your "success" handler, but I bet it's not what you think. Save this
outside the "$.ajax()" call:
var clicked = this;
$.ajax(
// ...
success: function(res) {
if (res) {
$(clicked).closest('tr').remove();
}
else {
// ...
}
}
);
Inside your request, $(this) is not the .remove
element. It's a closure problem.
So you can assign $(this) to a variable before and call it after
// assign this to a variable
var val = this;
// Use
$(val).closest('tr').remove(); // It worked for me
Instead of :
$(this).closest('tr').remove();
I got exactly the same error on $.get() request.
For me this is the most weird bug in jQuery (my version 1.8.3).
My reason for this error was TD element with ID set to "nodeName".
After change ID value to something else, the error dissapear.
Original:
<td id="nodeName"></td>
New:
<td id="nodeNameValue"></td>
精彩评论