Select all item where id isn't an id

江枫思渺然 提交于 2020-01-24 23:33:29

问题


All I want is that on item1 click to hide all items where id isn't item1.

The html:

<span id="select1">item1</span>
<span id="2">item1</span>
<div style="clear:both"></div>

<img src="http://www.lorempixel.com/100/100" id="item1">
<img src="http://www.lorempixel.com/100/100" id="item1">
<img src="http://www.lorempixel.com/100/100" id="item1">
<img src="http://www.lorempixel.com/100/100" id="item1">

<img src="http://www.lorempixel.com/100/100" id="item2">
<img src="http://www.lorempixel.com/100/100" id="item3">
<img src="http://www.lorempixel.com/100/100" id="item4">
<img src="http://www.lorempixel.com/100/100" id="item2">

This is the demo version: Demo


回答1:


As Madhu says, it is not validable HTML, but if you want to continue with it: http://jsfiddle.net/5kJTU/

$('#select1').on('click',function(){

    $('img').not("#item1").hide();

});



回答2:


After changing to class like Madhu suggested, user proper class selector in jquery $(".item1").hide();

eddited jsfiddle




回答3:


Your current code on there is simply missing the hash # before item1.hide()

$('#select1').click(function(){
    $('#item1').hide();
});

Madhu above is correct though. Consider changing to classes instead of ids if you will have repeat elements.




回答4:


Having same ids for multiple element in a single page is validated as an invalid markup. As per standards ids should be unique per element, so you just can not do this.

To overcome this issue you can change your id attribute to class and you can try this code:

Markup:

<span id="item1">item1</span> <!--do id like this-->
<span id="item2">item2</span> <!--do id like this-->

<div style="clear:both"></div>

<img src="http://www.lorempixel.com/100/100" class="item1"> <!--changed id to class-->
<img src="http://www.lorempixel.com/100/100" class="item1">
<img src="http://www.lorempixel.com/100/100" class="item1">
<img src="http://www.lorempixel.com/100/100" class="item1">
<img src="http://www.lorempixel.com/100/100" class="item2">
<img src="http://www.lorempixel.com/100/100" class="item2">
<img src="http://www.lorempixel.com/100/100" class="item2">
<img src="http://www.lorempixel.com/100/100" class="item2">

jQuery:

$(function(){  // doc ready block starts

    $('span[id^="item"]').on('click', function () {
       var show = this.id; // "item1" if item1 clicked
       $('img').hide();  // hide all img first
       $('.' + show).show(); // show only click matched
    });

});

Demo




回答5:


Using same id for the different elements is not a good approach. Instead use it this way.

 $('#select1').click(function(){
$(".item1").hide();
});

I have updated your fiddle and im attaching it along with the answer. Refer the fiddle:http://jsfiddle.net/eRg7h/2/



来源:https://stackoverflow.com/questions/23993267/select-all-item-where-id-isnt-an-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!