刷新jQuery变量的值

时间:2016-02-06 00:09:47

标签: php jquery ajax

我正在使用此ajax调用加载php页面。第一次工作很棒,但我想重新加载(用户可以尝试多个答案)。但是,在第二次加载时,变量theAnswer保留第一次尝试的值。

$('body').on("click", "#answer-submit", function() {
    var theAnswer = $('#challenge-answer').val();
    //alert(theAnswer);
    $.ajax({    
    type: "POST",
        url: "ajax/answer.php",
        data: { answer : theAnswer },
        dataType: "html",
        success: function(msg){
            if(parseInt(msg)!=0) {
                $('#answer').html(msg);
            }
        }
    }); 
});

这是HTML

<div id=question-form>
    <input type=text name=answer id=challenge-answer class=clue-input /><br />
    <button id=answer-submit>GO</button>
</div>

2 个答案:

答案 0 :(得分:0)

我建议您直接在按钮上直接应用onclick

var button = $(#answer-submit);
button.onclick(function(e){
    e.preventDefault(); 
    var chanswer= $('#challenge-answer').val();
    $.ajax({    
         type: "POST",
         url: "ajax/answer.php",
         data: { answer : theAnswer },
         dataType: "html",
         success: function(msg){
         if(parseInt(msg)!=0) {
            $('#answer').html(msg);
        }
    }
}); 

});

答案 1 :(得分:0)

第一次尝试后,另一个#challenge-answer被添加到DOM?如果是这样,你的选择器将继续抓住第一个。在这个例子中,我添加了console.log($('[id="challenge-answer"]'));所以每次点击GO后你都可以看到是否有多个。

<强> http://jsfiddle.net/L4h4LLL4/4/

HTML:

<div id="fiddleBody">
  <div id=question-form>
    <input type=text name=answer id=challenge-answer class=clue-input /><br />
    <button id=answer-submit>GO</button>
  </div>
</div>

JS:

$('#fiddleBody').on("click", "#answer-submit", function() {
    console.log($('[id="challenge-answer"]'));
    var theAnswer = $('#challenge-answer').val();
    alert(theAnswer);
    /*
    $.ajax({    
    type: "POST",
        url: "ajax/answer.php",
        data: { answer : theAnswer },
        dataType: "html",
        success: function(msg){
            if(parseInt(msg)!=0) {
                $('#answer').html(msg);
            }
        }
    });
    */
});