繁体   English   中英

如何在首次加载页面时自动加载带有Ajax和jQuery的某个网页内容?

[英]How to automatically load a certain webpage content with Ajax and jQuery when page is first loaded?

当打开我的网页时,没有 Ajax 内容加载,直到单击其中一个链接然后显示连接到该链接的内容。

这是将内容加载到 ext-content 主网页的地方:

<main>
    <article class="ext-content">

    </article>
    </main>

这是 javascript,它在单击其中一个链接时加载内容:

$('section li').click(function() {
    $.ajax({
      type: 'GET',
      url: 'includes/ext-content/'+$(this).data('content')+'.html',
      dataType: 'html',
      success: function(response) {
        $('.ext-content').html(response);
      }
    });
  });

这些是点击时将内容加载到 ext-content 中的链接:

<section id="section-links">
      <p>Kies een van de onderstaande opties:</p>
      <ul id="componenten-links">
        <li data-content="cpu-shop">CPU's</li>
        <li data-content="moederbord-shop">Moederborden</li>
        <li data-content="geheugen-shop">Geheugen</a></li>
        <li data-content="hardschijf-shop">Harde schijven</a></li>
        <li data-content="grafischekaart-shop">Grafische kaarten</a></li>
        <li data-content="voeding-shop">Voedingen</a></li>
        <li data-content="behuizing-shop">Behuizingen</a></li>
      </ul>
    </section>

下面的代码会在页面加载时自动加载特定的网页,但这只有在我手动输入网页时才有效。html。 有没有办法让下面的代码工作,它会自动采用上面列出的链接之一,而不是我必须输入特定的网页。html? 否则我需要为每个网页使用不同的脚本。

 $('section li').ready(function() {
    $.ajax({
      type: 'GET',
      url: 'includes/ext-content/cpu-shop.html',
      dataType: 'html',
      success: function(response) {
        $('.ext-content2').html(response);
      }
    });
  });

谢谢您的帮助

考虑以下。

$(function(){
  $('.ext-content').load('includes/ext-content/' + $('section li').eq(0).data('content') + '.html');
  
  $('section li').click(function() {
    $('.ext-content').load('includes/ext-content/' + $(this).data('content') + '.html');
  });
});

查看更多: https://api.jquery.com/load/

当使用不带后缀选择器表达式的 URL 调用 .load .load()时,内容会在脚本被删除之前传递给.html() 这会在脚本块被丢弃之前执行它们。 但是,如果调用 .load .load()时带有附加到 URL 的选择器表达式,则脚本会在更新 DOM 之前被删除,因此不会被执行。

当页面准备就绪时,这将加载第一个LI并收集它的data属性。

$('section li').load(function() {
    $.ajax({
      type: 'GET',
      url: 'includes/ext-content/cpu-shop.html',
      dataType: 'html',
      success: function(response) {
        $('.ext-content2').html(response);
      }
    });
  });

使用 load 方法而不是 ready。

您可以使用document.ready在页面加载时加载数据。

$( document ).ready(function() {
$.ajax({
      type: 'GET',
      url: 'includes/ext-content/cpu-shop.html',
      dataType: 'html',
      success: function(response) {
        $('.ext-content2').html(response);
      }
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM