簡體   English   中英

如何隱藏使用外部代碼插入頁面的元素

[英]How to hide an element that is inserted to the page with external code

我想隱藏一個使用外部應用程序插入/注入到我的 Shopify 商店的元素。 大約一秒鍾后,網站上的所有內容都完成加載后,它出現了,並且有一個名為“hidethis”的 class 和一堆其他元素。

這沒有用,我不知道還有什么可以嘗試的。

$(".hidethis").hide();

我正在嘗試通過以下方式根據用戶的位置隱藏此元素:

 jQuery.ajax( {
  url: '//api.ipstack.com/check?access_key=xxx&fields=country_code',
  type: 'POST',
  dataType: 'jsonp',
  success: function(location) {



    if (location.country_code === 'EE') {


  $(function() {
  // if geolocation suggest you need to hide, execute this as soon as possible
  var sheet = window.document.styleSheets[0];
  sheet.insertRule('.cart__options { display:none; }', sheet.cssRules.length);




})

  } 
 }
} );

最佳解決方案:CSS

.hidethis { display:none }

如果這是不可能的,你需要 JS

  var sheet = window.document.styleSheets[0];
  sheet.insertRule('.hidethis { display:none; }', sheet.cssRules.length);

 $(function() { // if geolocation suggest you need to hide, execute this as soon as possible var sheet = window.document.styleSheets[0]; sheet.insertRule('.hidethis { display:none; }', sheet.cssRules.length); // test code - remove this when you insert the above code in your page setTimeout(function() {$("#container").append('<div class="hidethis">Hide this</div>');}, 1000); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"></div>

轉換為您的 Ajax 示例:

$.ajax({
  url: '//api.ipstack.com/check?access_key=xxx&fields=country_code',
  type: 'POST',
  dataType: 'jsonp',
  success: function(location) {
    if (location.country_code === 'EE') {
      var sheet = window.document.styleSheets[0];
      sheet.insertRule('.hidethis { display:none; }', sheet.cssRules.length);
    }
  }
})

或者添加一個

<style>.hidethis { display:none }</style> 

到您要隱藏的內容將出現之前的頁面。 然后在你的 ajax 做

if (location.country_code != 'EE') { $(".hidethis").show() }

你也可以試試間隔

 $(function() { var tId = setInterval(function() { var $hide = $(".hidethis"); if ($hide.length>0) { clearInterval(tId); $hide.hide(); } },500); // test code - remove this when you insert the script in your page setTimeout(function() { $("#container").append('<div class="hidethis">Hide this</div>'); },1000); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"></div>

這是一個如何添加事件的示例:
https://stackoverflow.com/a/48745137/155077

功能等同於.on

無需添加事件處理程序,您只需將其隱藏即可。

subscribeEvent(".feed", "click", ".feed-item", function (event) { /* here comes code of click-event*/ });

整個事情與 MutationObserver 一起工作:

// Options for the observer (which mutations to observe)
let config = { attributes: false, childList: true, subtree: true };

// Create an observer instance linked to the callback function
let observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(nodeToObserve, config);

回調:

// Callback function to execute when mutations are observed
let callback:MutationCallback = function (
    mutationsList: MutationRecord[], 
    observer: MutationObserver)
{
    for (let mutation of mutationsList)
    {
        // console.log("mutation.type", mutation.type);
        // console.log("mutation", mutation);

        if (mutation.type == 'childList')
        {
            for (let i = 0; i < mutation.addedNodes.length; ++i)
            {
                let thisNode: Node = mutation.addedNodes[i];
                allDescendants(thisNode); // here you do something with it
            } // Next i 

        } // End if (mutation.type == 'childList') 
        // else if (mutation.type == 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.');

    } // Next mutation 

}; // End Function callback 

您的問題實際上與外部應用程序添加的元素無關,問題是當您執行隱藏元素的代碼時,該元素尚未在 DOM 上。 因為在您的所有 JavaScript 代碼已經執行之后的某個時候添加該元素。

因此,您必須在添加元素后執行代碼。 一種方法是使用MutationObserver

這是一個簡單的示例,使用 MDN 中的示例作為參考:

<div id="some-id"></div>
// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
const config = { childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    for(let mutation of mutationsList) {
        if (mutation.type === 'childList') {
            document.querySelector('.hide').style.display = 'none';
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Add a timeout to simulate JavaScript being executed after all your code was executed.
setTimeout(() => {
    document.getElementById('some-id').innerHTML = '<span class="hide">Hello world</span>';
}, 1000);

1:首先,您在瀏覽器中檢查並找到元素 2:使用 $(document).ready() 並隱藏該元素

暫無
暫無

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

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