使用jquery删除按钮单击时的旧数据

时间:2016-07-03 01:57:05

标签: jquery ajax

所以我面临的问题是每次点击提交按钮时,ajax都会添加

$(function (){
    var $temp = $('#numberTemp');
    var $namex = $('#cityName');
    var $description = $('#description');
    var $wind = $('#wind');
    var $cloudiness = $('#cloudiness');
    var $humidity = $('#humidity');
    var $pressure = $('#pressure');
    var $mintemp = $('#mintemp');
    var $maxtemp = $('#maxtemp');

    $('#submitbtn').click(function(){
        var location = $('#inputtxt').val();
        $.ajax({
            type: 'GET',
            url: "http://api.openweathermap.org/data/2.5/weather?q="+location+"&units=",
            success: function(data){
                $temp.append('<h2>'+data.main.temp+'</h2>');
                $namex.append('<h2>'+data.name+'</h2>');
                $description.append('<p>'+data.weather[0].description+'</p>');
                $wind.append('<td>'+data.wind.speed+'</td>');
                $cloudiness.append('<td>'+data.weather[0].main+'</td>');
                $humidity.append('<td>'+data.main.humidity+'</td>');
                $pressure.append('<td>'+data.main.pressure+'</td>');
                $mintemp.append('<td>'+data.main.temp_min+'</td>');
                $maxtemp.append('<td>'+data.main.temp_max+'</td>');
            }

        });
    });
});

/**
$.each(data,function(index, data){
    if (index === "main") {
        $temp.append('<h2>'+data.temp+'</h2>');
    }

});
**/

我希望每次单击“提交”按钮时都重置新数据。我能以任何方式做到这一点吗?

1 个答案:

答案 0 :(得分:1)

您只需要替换新值而不是仅仅添加新值。因此,使用.html()函数而不是.append()函数:

$(function (){
    var $temp = $('#numberTemp');
    var $namex = $('#cityName');
    var $description = $('#description');
    var $wind = $('#wind');
    var $cloudiness = $('#cloudiness');
    var $humidity = $('#humidity');
    var $pressure = $('#pressure');
    var $mintemp = $('#mintemp');
    var $maxtemp = $('#maxtemp');

    $('#submitbtn').click(function(){
        var location = $('#inputtxt').val();
        $.ajax({
            type: 'GET',
            url: "http://api.openweathermap.org/data/2.5/weather?q="+location+"&units=",
            success: function(data){
                $temp.html('<h2>'+data.main.temp+'</h2>');
                $namex.html('<h2>'+data.name+'</h2>');
                $description.html('<p>'+data.weather[0].description+'</p>');
                $wind.html('<td>'+data.wind.speed+'</td>');
                $cloudiness.html('<td>'+data.weather[0].main+'</td>');
                $humidity.html('<td>'+data.main.humidity+'</td>');
                $pressure.html('<td>'+data.main.pressure+'</td>');
                $mintemp.html('<td>'+data.main.temp_min+'</td>');
                $maxtemp.html('<td>'+data.main.temp_max+'</td>');
            }

        });
    });
});