简体   繁体   中英

Hide id dynamically by jquery

I have three 3 divs

<div id= "product_1"></div>
<div id= "product_2"></div>
<div id= "product_3"></div>
<div id= "product_4"></div>
<div id= "product_5"></div>

I am changing the ids dynamically

var hotelCode = "CUNMXHIDD,CUNMXMAYA,CUNMXDSAN"
var splittedHotelCode = hotelCode.toString().split(',');
jQuery.each(splittedHotelCode, function(i, hotelCode) {
 $("#product_"+ i).attr("id","product_"+ hotelCode);
});

After this I want to hide divs which are not been indexed product_4 and product_5

Now DOM is

<div id= "product_CUNMXHIDD"></div>
<div id= "product_CUNMXMAYA"></div>
<div id= "product_CUNMXDSAN"></div>
<div id= "product_4"></div>
<div id= "product_5"></div>

I dont want to hard code. Is it possible I can hide them by Jquery ?

您可以使用数组的lengthslice方法。

$('div[id^=product]').slice(splittedHotelCode.length).hide();
  1. Keep track of index to preserve the last index
  2. Use :gt() to select and then hide all elements that have id that start with product_

var hotelCode = CUNMXHIDD,CUNMXMAYA,CUNMXDSAN
var splittedHotelCode = hotelCode.toString().split(',');
var lastIndex = 0;
jQuery.each(splittedHotelCode, function(i, hotelCode) {
 $("#product_"+ i).attr("id","product_"+ hotelCode);
 lastIndex = i;
});

$('[id^="product_"]:gt('+lastIndex+')').hide();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM