1

为什么这里的 HTML 值在函数执行后几乎立即消失在 .name div 中?

$('input[type="submit"]').click(function (e) {
    value = $("#txtName").val();
    $(".name").text(value);
});
4

3 回答 3

3

Assuming that there's no other code on the page, your code isn't canceling the postback which will re-load the page. You could call e.preventDefault(); on the first line of the handler to prevent submission.

A better option would be to handle the submit() event of the form rather than listening for any clicks on submit buttons. This will properly handle a form submission from all sources (keypress, etc.):

$('#yourFormId').submit(function(){
    value = $('#txtName').val();
    $('.name').text(value);
    return false; // prevents submission
});
于 2013-06-07T15:47:47.353 回答
3

A post back is occurring, cancel the default action:

$('input[type="submit"]').click(function (e) {
    e.preventDefault();
    value = $("#txtName").val();
    $(".name").text(value);
});
于 2013-06-07T15:48:03.023 回答
0

This happen because you have a Submit action that supmit the form collection and reset your fields. To resolve this problem change your code as following :

$('input[type="submit"]').click(function (e) {
e.preventDefault();
value = $("#txtName").val();
$(".name").text(value);

// if you would like to submit then :
$('form').submit();

});

于 2013-06-07T15:52:07.300 回答