Multiple lists, js operation hides the same property value in the same row

Keywords: Attribute JQuery Javascript IE

Demand scenario:

Select a product and display the different attributes of all stores. Each ul represents a store, and each line of li represents an attribute

The effect is as follows:

Click to display all: After clicking the hide the same item button:

Solution:

Hide button implementation:

Traversing ul, traversing li in each url

When traversing the first ul's li, the value of each li is added to the attr array as the initial value for comparison, and a data array is used to indicate that it is repeated by default

After the second ul traversal, the value of li removal is compared with that of attr. If it is different, the coordinate corresponding to data is marked as false, and if it is the same, it is still true (Note: if it is already false, it can no longer be marked as true);

Traverse ul and li, assign the text value of the same li to the new attribute value2 according to the data array, and replace the text with/

Display button implementation:

Assign the value of value2 in the li tag to text

html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery.1.9.1.min.js.js" type="text/javascript"></script>
</head>
<body>
 <ul>
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
	<li>0</li>
 </ul>
  <ul>
	<li>2</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
	<li>5</li>
 </ul>
  <ul>
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>3</li>
	<li>5</li>
 </ul>
 <button onclick="hideFn()">Hide the same</button>
  <button onclick="showFn()">Show all</button>
<script>

	function hideFn(){
	 var data=[];
	 var attr=[];
	 $.each($('ul'), function(index,item){
		$.each($(item).children(),function(i){
			if(index==0){
			
				attr.push($(this).text());
				data.push(true);
			}
			if($(this).text()==attr[i]){
				data[i]= data[i]==false?false:true;
			}else{
				data[i]=false;
			}
		});
		
	 }); 
	 
	 $.each($('ul'), function(index,item){
		$.each($(item).children(),function(i){
			if(data[i]==true){
				if($(this).text()!='/'){
					$(this).attr("value2",$(this).text());
				}
				$(this).text('/');
			}
		});
		
	 }); 
	}
	
	function showFn(){
		$.each($('ul'), function(index,item){
		$.each($(item).children(),function(i){
			if($(this).attr("value2")){
				$(this).text($(this).attr("value2"));
			}
			
		});
		
	 }); 
	}
	
</script>
</body>
</html>

 

Note: when assigning value attribute of li, you get 0. You need to customize an attribute so that the child can assign successfully.

Reason: the value defined by li in ul will be automatically converted to int. value. In ie browser, it is greater than int max. value, and int max. value will be displayed. In other browsers, it will be 0. No matter what value you define, it will be converted to int. the default value is 1,

 

Posted by André D on Sat, 28 Dec 2019 06:40:25 -0800