簡體   English   中英

在內部渲染HTML <script> Tag

[英]Rendering HTML Within <script> Tag

我使用以下代碼向頁面中注入一些HTML:

    <script>    
window.onload = function() {
  addHeader();
};
    </script>

<script>function addHeader(){$("#header-nav-studio").after('<li id="header-nav-products" class="has-subnav"> <a href="/LiveCustom/Stores/Page/1000025/Apparel_Pricing">Pricing  <span class="arrow-down"></span> </a> <div class="header-subnav"> <ul> <li><a href="http://livecustom.com/LiveCustom/Stores/Page/1000025/Apparel_Pricing"> Apparel Pricing</a></li><li><a href="https://livecustom.com/LiveCustom/Full_Color_Vinyl_Stickers-Products/1000036"> Sticker Pricing</a></li><li><a href="https://livecustom.com/LiveCustom/Pinback_Buttons-Products/1000039"> Pinback Button Pricing</a></li></ul> </div></li>')}</script>

它可以直接在“#header-nav-studio” DIV之后加載所有內容。 唯一的問題是,它無法在腳本中正確呈現HTML。 應該會生成一個“定價”下拉菜單。 相反,它僅用作鏈接。 您可以在此處看到示例

有沒有辦法在script標簽內正確加載html或從外部源加載html? 非常感謝!

看起來您需要在動態添加的DOM元素上綁定mouseover事件,以觸發子菜單外觀。

在具有has-subnav類的li元素上,存在mouseover事件偵聽器,該事件偵聽器在其上切換active css類。

您需要更改JavaScript,因此即使是動態創建的元素也要附加事件。 您可以在父選擇器上使用$.on()附加處理程序。

$('body').on('mouseover', '.has-subnav', function() {
   $(this).addClass('.active');
});
//and to remove class on mouseout
$('body').on('mouseover', '.has-subnav', function() {
   $(this).removeClass('.active');
});

在您共享的示例中,定價菜單項的ID與產品菜單項的ID相同。 具有相同id的兩個節點可能會產生意外結果。 我會說先將ID更改為“ header-nav-pricing”,然后重試您的代碼。

暫無
暫無

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

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