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 ?
您可以使用数组的length
和slice
方法。
$('div[id^=product]').slice(splittedHotelCode.length).hide();
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.