2015-02-09 29 views
0

我正在嘗試編寫一些JS,它將查找特定的主體類,並用大塊HTML替換頁面上找到的空白內容。在具有特定主體類的頁面上填充空div div

換句話說,我希望JS在具有「ly_productdetails ProductDetails en en_GB」主體類的頁面上觸發並注入一些特定的HTML。

我是一個JS noob所以不太確定我在做什麼錯在這裏。

$(document).ready(function() { 
     if ($('body.ly_productdetails ProductDetails en  en_GB').length > 0) { 
     var element = document.getElementById("container"); 
     element.innerHTML = "<div><h1>Products</h1></div>"; 
    } 
}); 

http://jsfiddle.net/du5rtfw7/

任何提示,將不勝感激。

感謝

+1

檢查如何讓jQuery選擇與幾個班的第二個例子http://api.jquery.com/class-selector/ – kontur 2015-02-09 11:57:57

+0

如果你希望它是所有這些類的主體,選擇器應該是'body.ly_productdetails.ProductDetails.en.en_GB'這些空格表示具有'en'類的元素中具有'en_GB'類的任何元素。在'主體內的ProductDetails內。ly_productdetails' - http://jsfiddle.net/du5rtfw7/1/ – Pete 2015-02-09 11:58:49

+0

謝謝皮特。這工作完美:) – 2015-02-09 12:16:15

回答

1

如果ly_productdetailsProductDetailsenen_GB都是類名,你應該做的:body.ly_productdetails.ProductDetails.en.en_GB

順便說一句,你可以做到這一點沒有jQuery的:

document.addEventListener("DOMContentLoaded", function() { 
    if (document.querySelector("body.ly_productdetails.ProductDetails.en.en_GB")) { 
    var element = document.getElementById("container"); 
    element.innerHTML = "<div><h1>Products</h1></div>"; 
    } 
} 

(編輯)好了,jQuery的版本:

$(document).ready(function() { 
    if ($("body.ly_productdetails.ProductDetails.en.en_GB").length > 0) { 
    var element = document.getElementById("container"); 
    element.innerHTML = "<div><h1>Products</h1></div>"; 
    } 
} 
+0

雖然我認爲最好用jQuery來演示它。如果他是綠色的,那麼輸入本地功能就會混淆。 – Viktor 2015-02-09 12:03:21

+1

@ViktorCarlén哦,我同意並且只是增加了jQuery版本。 :D – 2015-02-09 12:06:18

+0

這些小點確實有效。謝謝(是的,此刻非常綠) – 2015-02-09 12:17:46

1

嘗試用:

$(function(){ 
    if ($('body.ly_productdetails.ProductDetails.en.en_GB').length > 0) { 
     $('#container').html('<div><h1>Products</h1></div>'); 
    } 
}); 

您只需使用錯誤的CSS查詢..

0

孜然要檢查是否#container是空克,這樣做在jQuery的使用.is(':empty')

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<body class="ly_productdetails ProductDetails en en_GB"> 
 
    <div id="container"></div> 
 
    <script> 
 
    $(document).ready(function(){ 
 
     if ($('body.ly_productdetails.ProductDetails.en.en_GB').length > 0) { 
 
     if ($('div#container').is(':empty')) { 
 
      $('div#container').html("<div><h1>Products</h1></div>"); 
 
     } 
 
     } 
 
    }); 
 
    </script> 
 
    <p>Empty container gets populated</p> 
 
</body>

Updated jsFiddle

電文讀出:

0

你有幾個真正好的答案,我會在短短的芯片,並說一個匹配的功能是什麼,我會更喜歡使用(它的速度)。

$(function() { // document ready 
    var body = $(document.body); // body element 

    // If match and length then modify html 
    if (body.attr('class').match(/ly_productdetails ProductDetails en en_GB/).length > 0) { 
     $('#container').html("<div><h1>Products</h1></div>"); 
    } 
}); 

小提琴:http://jsfiddle.net/34svmabn/

速度測試:http://jsperf.com/hasclass-vs-is-stackoverflow/7

+0

這很有趣。所以從性能的角度來看,使用「匹配」會更好?謝謝 – 2015-02-09 12:21:19