简体   繁体   English

突出显示和取消突出显示在jQuery中选择的项目

[英]highlight and un-highlight item selected in jquery

I have a dynamic list of image thumbnails. 我有图像缩略图的动态列表。 Every time an image is selected I want to unselect the currently selected image and select the newly clicked image. 每次选择图像时,我要取消选择当前选择的图像,然后选择新单击的图像。 The html looks like below: HTML如下所示:

<ul class="imgList">
    <li>
        <div id="item1" class="imgStyle" order="{#}" imgId="{imgId}">
            <img src="{imgPath}"/>
        </div>
    </li>
    <li>
        <div id="item2" class="imgStyle" order="{#}" imgId="{imgId}">
            <img src="{imgPath}"/>
        </div>
    </li>
    <li>
        <div id="itemn" class="imgStyle" order="{#}" imgId="{imgId}">
            <img src="{imgPath}"/>
        </div>
    </li>
</ul>

And I use jquery to bind the items on click event like this: 而且我使用jQuery来绑定单击事件上的项目,如下所示:

$( ".imgStyle img").bind( "click", function() {
    $(item1).css("border", "5px solid grey");
}

I'm easily able to select/highlight the item clicked. 我可以轻松选择/突出显示单击的项目。 But how do I unselect the previously highlighted item (div)? 但是,如何取消选择以前突出显示的项目(div)? Thanks! 谢谢!

You should use CSS classes : 您应该使用CSS类:

.selected { border: 5px solid gray;}

$('.imgList').on('click','img', function() {
   $(this).parents('.imgList').find('.selected').removeClass('selected').end().end().addClass('selected');
});

I seldom directly manipulate the css style, but rather add a class and when it is no longer in use, I simply remove the class. 我很少直接操作css样式,而是添加一个类,当不再使用它时,我只是删除该类。

eg 例如

$( ".imgStyle img").bind("click", function() {
    $(".imgStyle").removeClass("highlight");
    $(item1).addClass("highlight");
}

Following the method you are already doing: 按照您已经在做的方法:

$( ".imgStyle img").bind( "click", function() {
    $( ".imgStyle img").removeAttr("style");
    $(item1).css("border", "5px solid grey");
}

Since the jquery's .css() method adds the property to the inline style attribute of the element, removing this style of everyother img should be enough 由于jquery的.css()方法将属性添加到元素的内联style属性中,因此删除其他img的这种样式就足够了

BUT

You'd better use a class to define a selected element, like: 您最好使用一个类来定义选定的元素,例如:

.selected {
    border: 5px solid gray;
}

And then: 接着:

$(".imgStyle img").bind("click", function() {
    $(".selected").removeClass("selected");
    $(this).addClass("selected");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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