简体   繁体   English

如何隐藏使用外部代码插入页面的元素

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

I'd like to hide an element that is inserted/injected to my Shopify store with an external app.我想隐藏一个使用外部应用程序插入/注入到我的 Shopify 商店的元素。 It appears about a second later after everything has finished loading on the site and has a class called "hidethis" and a bunch of other elements.大约一秒钟后,网站上的所有内容都完成加载后,它出现了,并且有一个名为“hidethis”的 class 和一堆其他元素。

This did not work and I have no idea what else to try.这没有用,我不知道还有什么可以尝试的。

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

I'm trying to hide this element based on the location of the user in the following manner:我正在尝试通过以下方式根据用户的位置隐藏此元素:

 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);




})

  } 
 }
} );

Best solution: CSS最佳解决方案:CSS

.hidethis { display:none }

If this is not possible and you need JS如果这是不可能的,你需要 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>

which translates to your Ajax example:转换为您的 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);
    }
  }
})

Alternatively add a或者添加一个

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

to the page before where the content you want to hide is going to appear.到您要隐藏的内容将出现之前的页面。 Then in your ajax do然后在你的 ajax 做

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

You can also try an interval你也可以试试间隔

 $(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>

Here an example how to add events:这是一个如何添加事件的示例:
https://stackoverflow.com/a/48745137/155077 https://stackoverflow.com/a/48745137/155077

functional equivalent to jQuery .on .功能等同于.on

Instead of adding an event-handler, you'll just have to hide it.无需添加事件处理程序,您只需将其隐藏即可。

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

The whole thing works with MutationObserver:整个事情与 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);

where callback:回调:

// 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 

Your problem isn't actually about an element being added by an external app, the problem is that when your code to hide the element is executed the element isn't on the DOM yet.您的问题实际上与外部应用程序添加的元素无关,问题是当您执行隐藏元素的代码时,该元素尚未在 DOM 上。 Because the element is being added sometime later after all your JavaScript code was already executed.因为在您的所有 JavaScript 代码已经执行之后的某个时候添加该元素。

So, you have to execute your code after the element is added.因此,您必须在添加元素后执行代码。 One way to do that is by using MutationObserver .一种方法是使用MutationObserver

Here is a simple example using as referece the example in MDN:这是一个简单的示例,使用 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: at first, you inspect in your browser and find the element 2: use $(document).ready() and hide that element 1:首先,您在浏览器中检查并找到元素 2:使用 $(document).ready() 并隐藏该元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM