如何在javascript中使用新数据重新加载页面



当我第一次加载网页时,我调用此函数来加载数据。

 function campusInfo(id) {

(调用第三方 API 并获取要在页面上显示传入的 ID 的数据......

我在同一页面上有一个超链接,单击该超链接时它会调用相同的函数并传入一个新 id。我希望当单击此超链接时,页面应该加载此 id 独有的新数据,而是加载数据,但将其附加到初始加载时页面上已存在的数据。单击此超链接时,我需要以某种方式清除页面中的旧数据。这是我的超链接代码:请注意,我使用的是div而不是实际的超链接并调用campusInfo((函数。

 $(r.campuses).each(function (index, item) {
            if (item.campusID != id) { // checks if the current other schools id is not equal to current page main school id 
                    var HTMLcontentSchool = '<div class="ml-32 mt-16 mb"><div class="other-school" onclick="campusInfo(' 
                    + item.campusID + ')"><label class="other-schools-list">' + item.campusName + '</label></div><br /></div>';
                    $('.group').append(HTMLcontentSchool);                     
                }

如果元素$('.group')除了里面的数据之外什么都没有,你可以使用 $.empty 函数清除它的所有内容。这样:

 $(r.campuses).each(function (index, item) {
    if (item.campusID != id) { // checks if the current other schools id is not equal to current page main school id 
            var HTMLcontentSchool = '<div class="ml-32 mt-16 mb"><div class="other-school" onclick="campusInfo(' 
            + item.campusID + ')"><label class="other-schools-list">' + item.campusName + '</label></div><br /></div>';
            $('.group').empty();  // <----------------------Empties contents
            $('.group').append(HTMLcontentSchool);                     
        }

否则,如果还有其他子元素需要保留,则必须保留对以前添加的节点的引用,以便以后删除。这样:

var addedData = null;
$(r.campuses).each(function (index, item) {
    if (item.campusID != id) { // checks if the current other schools id is not equal to current page main school id 
            var HTMLcontentSchool = '<div class="ml-32 mt-16 mb"><div class="other-school" onclick="campusInfo(' 
            + item.campusID + ')"><label class="other-schools-list">' + item.campusName + '</label></div><br /></div>';
            if (!!addedData) { addedData.remove() } // check is exists, if so, remove.
            addedData = $(HTMLcontentSchool) // wrap as a jQuery object
            $('.group').append(HTMLcontentSchool);                     
        }

最新更新