You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery load加载指定ID的div时如何执行该div内的JavaScript脚本

问题根因

jQuery的load()方法在使用「URL + 选择器」语法筛选加载内容时,会默认剥离返回结果里的所有<script>标签,避免意外执行全局脚本,因此你目标div内部的脚本会被直接丢弃,不会触发执行。

解决方案

修改Page1中原load调用的逻辑,改为先拉取完整页面内容,自行筛选目标区域,再手动执行目标区域内部的脚本即可。同时修复原代码中请求还未返回就提前清空加载状态的问题,完整修改后的点击事件代码如下:

$(document).on('click', 'a[rel*=charger_partiel]', function(f) { 
  f.preventDefault();
  const myId_to_update_here = $(this).data('ajax_id_to_update');    
  const myId_to_load_from_other_page = $(this).data('direction');       
  const afficher_chargement = $(this).data('afficher_espace_de_chargement');
  const id_chargement_devant_lien_partiel= $(this).data('id_image_de_chargement_devant_lien');
  const pageURL = $(this).attr('href');
  
  history.pushState(null, '', pageURL);
  const image_de_chargement = '<img src="images/facebook_style_loader.gif" />';
  const preloader_comme_facebook_et_youtube = image_de_chargement ;     
  
  if(id_chargement_devant_lien_partiel!='') {
    $('#'+id_chargement_devant_lien_partiel).html(image_de_chargement);
  }
  if(afficher_chargement=='Oui') {
    $('#'+myId_to_update_here).html(preloader_comme_facebook_et_youtube);
  }
  
  // 替换原来的load方法,改用$.get自行处理内容和脚本
  $.get(pageURL, function(res) {
    // 将返回的整页内容转为jQuery对象
    const $fullPage = $(res);
    // 筛选出你需要的目标ID的内容
    const $targetArea = $fullPage.filter('#' + myId_to_load_from_other_page);
    // 先把目标HTML插入到页面
    $('#'+myId_to_update_here).html($targetArea.html());
    // 仅提取目标区域内的script标签执行
    $targetArea.find('script').each(function() {
      if (this.src) {
        // 处理外链脚本
        const newScript = document.createElement('script');
        newScript.src = this.src;
        document.body.appendChild(newScript);
      } else {
        // 处理内联脚本
        eval(this.textContent);
      }
    });
  }).fail(function() {
    $('#'+myId_to_update_here).html('<p>Oupps.. There was an error making the AJAX request. Maybe your internet connection is slowing down.</p>');
  }).always(function() {
    // 所有请求结束后再清空加载状态
    if(id_chargement_devant_lien_partiel!='') {
      $('#'+id_chargement_devant_lien_partiel).html('');
    }
  });
  
  return false;
});

效果说明

该方案只会执行你指定的目标ID(本案例中为id_du_milieu)内部的脚本,目标ID外的其他脚本不会被处理,完全符合需求。

内容的提问来源于stack exchange,提问作者Man Of God

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:15:01