問題描述
根據 URL 變量過濾 HTML 內容 (Filtering HTML content based on URL Variable)
I am looking for a way that I can hide specific HTML content based on a variable in the URL.
For example, I am passing a variable: index.html?app=new
I have various images and other content that has a prod attribute and would like to show only those that have the "new" prod value.
<img prod="new" class="image" src="../images/screen.png" height="300" width="600"/>
I have used the following to harvest the url variable:
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
My problem is where to go from here
參考解法
方法 1:
I think this CSS rule will do the magic for you:
[prod]:not([prod=new]) { display:none; }
It will hide all elements having 'prod' attribute with the value other than 'new'.
方法 2:
This is untested code.
HTML
<img data‑prod="new" class="image" src="../images/screen.png" height="300" width="600" />
JavaScript
<script>
(function(){
'use strict';
var getUrlVars = function() {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
}
);
return vars;
};
if(typeof getUrlVars.app === 'string' && getUrlVars.app === 'new') {
var c = document.querySelectorAll('[data‑prod="new"]'), i;
for(i = 0; i < c.length; i+=1) {
c[i].style.display = 'none';
}
}
})();
</script>
In the general case (i.e. app=new, app=whatever), you can substitute new
in the querySelectorAll parameter as the variable itself:
if(typeof getUrlVars.app === 'string') {
var c = document.querySelectorAll('[data‑prod="' + getUrlVars.app + '"]'), i;
for(i = 0; i < c.length; i+=1) {
c[i].style.display = 'none';
}
}
(by kman、c‑smile、rink.attendant.6)