[英]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.