JQuery JS: с помощью двух отправленных форм и решить, что делать - PullRequest
0 голосов
/ 17 ноября 2010
function removeComment(bID) {
    $('#submitChangeComment').attr('disabled', true);
    $.ajax({ 
        type: "POST",
        url: "misc/changeComment.php",
        data: {
            mode: 'del',
            bID : bID,
            comment : $('input[name=Comment]:visible').val() 
        }, 
        success: function(msg){
            $('#submitChangef').attr('disabled', false);
            $('#currentComment' + bID).hide();

            var $msg = $("#nowCurrentComment" + bID).find('.comment');
            // if it already has a comment, fade it out, add the text, then fade it back in
            if ($msg.text().length) {
                $msg.fadeOut('fast', function() {
                    $msg.text(msg).fadeIn('fast');
                });
            } else {
                // otherwise just hide it, add the text, and then fade it in
                $msg.hide().text(msg).fadeIn('fast'); 
            }
        }
    });
}

function FriendChangeComment(bID) {
    $('#submitChangef').attr('disabled', true);
    $.ajax({ 
        type: "POST",
        url: "misc/changeComment.php",
        data: {
            mode: 'edit',
            bID : bID,
            comment : $('input[name=Comment]:visible').val() 
        }, 
        success: function(msg) {
            $('#submitChangef').attr('disabled', false);
            $('#currentComment' + bID).hide();

            var $msg = $("#nowCurrentComment" + bID).find('.comment');
            // if it already has a comment, fade it out, add the text, then fade it back in
            if ( $msg.text().length ) {
                $msg.fadeOut('fast', function() {
                    $msg.text( msg ).fadeIn('fast');
                });
            } else {
                // otherwise just hide it, add the text, and then fade it in
                $msg.hide().text( msg ).fadeIn('fast'); 
            }
        }
    });
}

Форма:

<form action="javascript:FriendChangeComment(<? echo $showInfo["bID"]; ?>)" method="post">
change comment for <br><?php echo fullname($showInfo["bID"]); ?>:<br>
<input type="text" name="Comment" value="<?=$showC["comment"];?>" size="20">  
<input name="submit" type="submit" id="submitChangef" value="Save">
<input name="removeC" type="button" id="submitremoveComment" value="remove" onClick="">
</form>

У меня есть две кнопки отправки в одной форме. Если вы нажмете первый «submitChangef», я хочу, чтобы он запускал FriendChangeComment (), если вы нажмете «removeComment», я хочу, чтобы он запускал removeComment. Обе функции одинаковы, единственная разница между ними заключается в режиме: (del, edit) в данных ajax. Я не знаю, как я могу сократить код и упростить его, так как они являются полными копиями друг друга (почти).

Как это можно сделать?

Ответы [ 2 ]

1 голос
/ 17 ноября 2010

Добавьте bID как скрытое поле ввода в форму и переместите привязку события в jQuery вместо того, чтобы делать это в самой форме, затем передайте bID и режим в качестве параметра функции:

$('#submitChangef').click(function() {
    bID = $(this).closest('form').find('#bID').val();
    changeComment(bID, 'edit');
    return false;
});

$('#submitremoveComment').click(function() {
    bID = $(this).closest('form').find('#bID').val();
    changeComment(bID, 'del');
    return false;
});

function changeComment(bID, mode) {
    $('#submitChangeComment').attr('disabled', true);
    $.ajax({ 
        type: "POST",
        url: "misc/changeComment.php",
        data: {
            mode: mode,
            bID : bID,
            comment : $('input[name=Comment]:visible').val() 
        }, 
        success: function(msg){
            $('#submitChangef').attr('disabled', false);
            $('#currentComment' + bID).hide();

            var $msg = $("#nowCurrentComment" + bID).find('.comment');
            // if it already has a comment, fade it out, add the text, then fade it back in
            if ($msg.text().length) {
                $msg.fadeOut('fast', function() {
                    $msg.text(msg).fadeIn('fast');
                });
            } else {
                // otherwise just hide it, add the text, and then fade it in
                $msg.hide().text(msg).fadeIn('fast'); 
            }
        }
    });
}
0 голосов
/ 17 ноября 2010

Я бы использовал одну функцию для ваших нужд и один скрытый параметр формы, например: form:

<form id='myform' method="post">
change comment for <br><?php echo fullname($showInfo["bID"]); ?>:<br>
<input type="text" name="Comment" value="<?=$showC["comment"];?>" size="20">  
<input name="submit" type="submit" onclick="processBtnClick(this, 'edit');" value="Save">
<input name="removeC" type="button" onclick="processBtnClick(this, 'remove');" value="remove" onClick="">
<input type='hidden' name='action' id='action'/>
</form>

js:

function processBtnClick(bID, action){
  $('#action').value(action);
  $('#myform').submit();

/ * или ваш .ajax-код $.ajax ({type: "POST", url: "misc / changeComment.php", ... * /}

php (или что-то еще):

 if ($_POST['action']=='remove')
      do_remove_stuff();
    else
      do_edit_stuff();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...