Как скрыть элемент, который вставлен на страницу с внешним кодом - PullRequest
1 голос
/ 14 октября 2019

Я хотел бы скрыть элемент, который вставляется / вводится в мой магазин Shopify с помощью внешнего приложения. Он появляется примерно через секунду после того, как все закончило загрузку на сайте и имеет класс с именем «hidethis» и кучу других элементов.

Это не сработало, и я понятия не имею, что еще можно попробовать.

$(".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);




})

  } 
 }
} );

Ответы [ 4 ]

0 голосов
/ 14 октября 2019

Ваша проблема на самом деле не в том, что элемент добавляется внешним приложением, проблема в том, что когда ваш код для скрытия элемента выполняется, элемент еще не находится в 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);
0 голосов
/ 14 октября 2019

Вот пример того, как добавить события:https://stackoverflow.com/a/48745137/155077

функциональный эквивалент jQuery .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 
0 голосов
/ 14 октября 2019

1: сначала вы проверяете в своем браузере и находите элемент 2: используйте $ (document) .ready () и скрываете этот элемент

0 голосов
/ 14 октября 2019

Лучшее решение: 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...