简体   繁体   中英

Why does the submit button only work when pressed twice on my example?

Please look at this fiddle:

http://jsfiddle.net/uNbYu/1/

When the submit button is pressed once, It removes the text edit for no apparent reason, but doesn't do anything, but the second time, it does work when pressed, and goes to the page.

Please help me with what makes this code do that.

Thanks


HTML:

<b class = "edit" id = "fooo"> FOO </b>

JS:

$('b.edit').click(function() {
    $(this).hide().after('<form action = "foo.php" method = post><input hidden name = "field" type = "text" value = "' + this.id + '"/><input type="text" name = "period" class="editP" value="' + $(this).html() + '" /><input type = "submit" value = "Submit!!" /></form>');
    $('.editP').focus();
});
$('.editP').live('blur', function() {
    $(this).hide().prev('b.edit').html($(this).val()).show();
});

This is what your code says:

  1. When text is clicked, create a new input element, submit button and form.
  2. On blur hide the input element (not the submit button)

So when you click submit the first time it is actually firing the blur event and hiding the input.

Also, your old text is not being reshown because you use .prev to get it. This select previous adjacent sibling, but because the input element is in a form, the other element is not a sibling.

This Fiddle should make what is wrong more obvious. Note how the initial alert does not retrieve the text FOO. Also try and click submit button.

http://jsfiddle.net/uNbYu/8/

问题在于,在您设法单击按钮之前,编辑框会失去焦点,从而更改了位置,以致您不会单击按钮。

1) When you click the text, your code creates the form and put the focus on .editP .

$('.editP').focus();

2) The rest of your code says to hide .editP when it loses focus (blur).

$('.editP').live('blur', function(){
    $(this).hide().prev('b.edit').html($(this).val()).show();
});

3) So the act of trying to click the button causes the blur event to trigger on editP . This hides .editP thus shifting over the button which prevents it from being clicked. It happens very fast... before you can actually successfully click the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM