过滤<p> </p>之间的所有内容的url,其中<h2> </h2> =值

时间:2018-06-25 14:21:37

标签: html url parameters

是否可以创建一个网址过滤器(www.website.com?filter=value),以便用户可以在<h2>标签中输入数据?

示例:

<p>
<h2>THIS</h2>
<div>information</div>
<h5>other info</h5>
<h2>THAT</h2>
<div>information2</div>
<h5>other info2</h5>
</p>

要检索html的一部分,用户将输入类似于www.website.com?h2=THIS的内容,然后返回:

<h2>THIS</h2>
<div>information</div>
<h5>other info</h5>

1 个答案:

答案 0 :(得分:1)

是的,有可能。您将需要一些Javascript来实现它。

//Array of the elements you are wanting
const sections = [
  {
		title: 'THIS',
    info1: 'information',
    info2: 'other info'
  },
  {
  	title: 'THAT',
    info1: 'information2',
    info2: 'other info2'
  }
]

//getting the URL and the parameters
var url_string = "http://www.website.com?h2=THIS"; //Can get this with window.location.href
var url = new URL(url_string);
var h2 = url.searchParams.get("h2");

//filtering through initial array and creating a new array based on the parameters value
let filteredSections = sections.filter((section) => {
	return section.title === h2
})

//Looping through the filtered array, creating each element and displaying it to HTML by appending it
filteredSections.forEach((section) => {
	let wrappingDiv = document.createElement('div')
  
  let h1Tag = document.createElement('h1')
  h1Tag.textContent = section.title
  
  let innerDiv = document.createElement('div')
  innerDiv.textContent = section.info1
  
  let h5Tag = document.createElement('h5')
  h5Tag.textContent = section.info2
  
  let bodyTag = document.querySelector('body')
  
  //appending everything in html
  bodyTag.appendChild(wrappingDiv)
  wrappingDiv.appendChild(h1Tag)
  wrappingDiv.appendChild(innerDiv)
  wrappingDiv.appendChild(h5Tag)
})
<html>
  <body>
    <!-- Javascript will create elements here -->
  </body>
</html>

希望这会有所帮助。让我知道您是否有任何疑问

相关问题