javascript - 如何用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);
}
推荐阅读
- java - JPA 使用 flush 来触发异常并停止执行
- python - How to determined if window in Maya exists?
- c - C[i] = A[i++]; 不等于 C[i] = A[i];我++;这里发生了什么?
- spring-boot - 如何在 spring-boot 中为不同的数据源设置不同的 Hikari 配置?
- datetime - 修改 Freemarker 日期
- python - 最后几行代码中的无限while循环
- django - 球队和球员之间的匹配表关系
- install4j - install4j DMG存档,设置附加文件的权限?
- oracle - 将多个值传递给替代变量并在查询中迭代
- python - 查找内置函数的调用而不是返回值