如何用Ajax和jQuery在页面首次加载时自动加载指定链接内容
解决方案
你需要修改页面加载时的自动执行逻辑,核心是自动获取第一个<li>元素的data-content属性值来拼接请求URL,无需手动指定具体路径,具体实现如下:
修改后的自动加载代码
$(document).ready(function() { // 获取第一个li的data-content属性值 const firstContentKey = $('#componenten-links li').first().data('content'); // 确保存在有效属性值再发起请求 if (firstContentKey) { $.ajax({ type: 'GET', url: 'includes/ext-content/' + firstContentKey + '.html', dataType: 'html', success: function(response) { $('.ext-content').html(response); }, error: function() { $('.ext-content').html('内容加载失败,请稍后重试'); } }); } });
额外优化:复用加载逻辑
为避免代码冗余,可将Ajax加载逻辑封装成通用函数,同时供点击事件和页面初始化调用:
// 封装通用加载函数 function loadExtContent(contentKey) { $.ajax({ type: 'GET', url: 'includes/ext-content/' + contentKey + '.html', dataType: 'html', success: function(response) { $('.ext-content').html(response); }, error: function() { $('.ext-content').html('内容加载失败,请稍后重试'); } }); } // 绑定li点击事件 $('section li').click(function() { loadExtContent($(this).data('content')); }); // 页面初始化时自动加载第一个li的内容 $(document).ready(function() { const firstContentKey = $('#componenten-links li').first().data('content'); if (firstContentKey) { loadExtContent(firstContentKey); } });
注意事项
你提供的链接HTML中,部分<li>标签错误使用了</a>闭合,需修正为</li>,避免HTML结构异常影响选择器功能。
内容的提问来源于stack exchange,提问作者Jameson
相关产品推荐
相关产品推荐

