簡體   English   中英

通過使用帶有href的查詢單擊div加載html

[英]Load html by click into div using query with href

我試圖根據href-clicking更改div內容。 我是自由格式寫法的新手,所以請對我保持溫柔。

因此,我有一個帶有<div> index.html,在其中加載了三個不同的本地html頁面(menu.html)->餐廳菜單。 在每個menu.html的開頭,我想在index.html中放置<a href> -用於更改菜單的鏈接。

我的問題是:用腳本調用的href鏈接位於menu.html內后,如何調用index.html?

到目前為止,我有:

  1. index.html會在div ID:“結果”中默認加載菜單“ alacarte.html”。
  2. 我想按“ alacarte.html”中的鏈接,使“ pizza.html”加載到index.html div id:“ result”中。
  3. 我真的希望將鏈接以圖形方式放在“ pizza.html”頁面的頂部。

在我的index.html中,我有:

<article class="post-meny" id="meny">
<script type="text/javascript">
   $(document).ready(function(){
       $("#alacarte").click(function(){
        $('#result').load('alacarte.html');
       });  
       $("#beverage").click(function(){
        $('#result').load('pizza.html');
       });  
       $("#beverage").click(function(){
        $('#result').load('beverage.html');
       });
   });
</script>
<div id="result"></div>

<script>
   $(document).ready(function(){
       $( '#result' ).load( 'alacarte.html' );
   });
</script>

</article>

然后在菜單頁面“ alacarte.html”

<!-- Links in restaurant menu that loads in index.html div id: result -->
<ul class="menu-navbar">
  <li>
     <a id="#pizza" href="#">PIZZA</a>
  </li>
  <li>
     <a id="#alacarte" href="#">A LA CARTE</a>
  </li>
  <li>
    <div id="#beverege" class="#">BEVERAGE</div>
  </li>
</ul>

<script type="text/javascript">
  $(document).ready(function(){

     $("#alacarte").click(function(){
         $('index.html#result').load('alacarte.html');
     });
     $("#beverage").click(function(){
         $('index.html#result').load('beverage.html');
     });
     $("#pizza").click(function(){
         $('index.html#result').load('pizza.html');
     }); 
  } 
 </script>

希望您能按照我徒勞的解釋。 我該怎么辦?

請幫忙!

由於您是將項目動態加載到index.html ,因此應使用.on()方法綁定並偵聽事件。 您無需在各個頁面本身中包含任何其他jQuery。

對於您的菜單,建議您在href屬性中包含預期的超鏈接,然后使用e.preventDefault()停止默認行為。

<ul class="menu-navbar">
  <li>
     <a href="pizza.html">PIZZA</a>
  </li>
  <li>
     <a href="alacarte.html">A LA CARTE</a>
  </li>
  <li>
    <a href="beverage.html">BEVERAGE</a>
  </li>
</ul>

index.html中 ,您可以利用.on()方法:

$(function() {
    // Use .on() to bind click even on dynamically added elements
    $(document).on('click', '.menu-navbar a', function(e) {

        // Prevents default behavior
        // Clicking on <a> will not redirect the page
        e.preventDefault();

        // Get hyperlink, and load page
        $('#result').load($(this).attr('href'));
    });

    // Load the first link by default, when DOM is ready
    $('#result').load('alacarte.html');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM