why jquery detach element will cause a form to submit?
i wonder why in the following example, trying to detach
an element (li
) causes 开发者_如何学Pythonthe form
containing it to submit
html
<form id="frmToDo" name="frmToDo">
<p id="lineInput">
...
<input type="submit" id="btnSubmit" value="Add" />
</p>
<ul id="todolist">
<!-- added in ajax -->
</ul>
</form>
JS
$("#frmToDo").submit(function() {
// this runs after: $("#todolist").detach(...)
});
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
I guess you just want to remove the li
element in which the button was clicked.
So instead of using
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
Try using
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$(this).parent().detach();
return false;
});
That's not a button, it's an input element.
$("#todolist").delegate("li[id^=task-] input:submit", "click", function() {
I am not sure if this is the cause of your problem but you are not using the detach
function correctly if your intention is to detach an li
element. The argument of the detach
function is a selector expression that filters the set of matched element in the jQuery element that you are calling the function on. In your code you call detach
on $('#todolist')
, which means you want to detach the todolist element, if it matches the argument passed.
You should do something like this instead :
$('#todolist li').detach(); //this will detach all the li elements
I am not sure if this can explain the fact that your form is submitting. If it is not : what event triggers the submit event of your form ? Maybe you use a button or input element that is placed inside the form and triggers the submit of the form ?
Unless there's some relevant code missing, you seem to assign a handler to the onclick
event outside a $(document).ready()
block. That makes it possible to run the assignment before the #todolist
is loaded, thus failing to find the buttons and attach handlers.
With no event cancelling, the default behaviur for a button is to submit the form.
Try this:
$(document).ready(function(){
$("#frmToDo").submit(function() {
// this runs after: $("#todolist").detach(...)
});
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
});
精彩评论