首页 > 解决方案 > 如何用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);                     
                }

标签: javascripthtml

解决方案


如果元素$('.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);                     
        }

推荐阅读