簡體   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