繁体   English   中英

jQuery选择类的所有元素(调用该函数的元素除外)

[英]jquery select all elements of class except the one that called the function

从数据源创建可变数量的div。 每个div内都有一个图像充当按钮,另一个div包含文本等。尽管实际用例稍微复杂一些,但我们可以在此处使用简化的版本:

<div id="main">
    <div id="content_block_1" class="content_block">
        <img id="content_block_button_1" class="content_block_button" src="images/1.png">
        <div id="content_block_textfield_1" class="content_block_textfield>
            This is text.
        </div>
    </div>
    <div id="content_block_2" class="content_block">
        <img id="content_block_button_2" class="content_block_button" src="images/2.png">
        <div id="content_block_textfield_2" class="content_block_textfield>
            This is more text.
        </div>
    </div>
    <div id="content_block_3" class="content_block">
        <img id="content_block_button_3" class="content_block_button" src="images/3.png">
        <div id="content_block_textfield_3" class="content_block_textfield>
            This is even more text.
        </div>
    </div>
</div>

通过单击图像,用户应能够将关联的文本字段的背景颜色变为黄色。 如果文本字段已经是黄色,则其背景设置应恢复为正常。 如果在某个文本字段已突出显示的情况下打开一个文本字段的黄色突出显示,则它应删除那些突出显示并仅激活新的。

我知道使用toggle()函数添加/删除.highlight CSS类。 这是我想到的一个非常不灵活的函数:

//1st
$('#content_block_button_1').click(function () {
    //toggle the corresponding 
    $('#content_block_textfield_1').toggleClass('highlight');
    //reset all other highlights
    $('#content_block_textfield_2, #content_block_textfield_3').removeClass('highlight');
    console.log("toggled highlight 1");
});

//2nd
$('#content_block_button_2').click(function () {
    //toggle the corresponding 
    $('#content_block_textfield_2').toggleClass('highlight');
    //reset all other highlights
    $('#content_block_textfield_1, #content_block_textfield_3').removeClass('highlight');
    console.log("toggled highlight 2");
});

//3rd
$('#content_block_button_3').click(function () {
    //toggle the corresponding 
    $('#content_block_textfield_3').toggleClass('highlight');
    //reset all other highlights
    $('#content_block_textfield_1, #content_block_textfield_2').removeClass('highlight');
    console.log("toggled highlight 3");
});

我想我们都可以同意这不是一个非常优雅,有效的代码。 而且它根本无法很好地扩展。

我想利用一个事实,即按钮和文本字段元素嵌套在同一“父”对象中。 而且,我想找到一种方法来从所有文本字段元素中删除“ .highlight”,这是所谓的“兄弟”按钮元素调用函数。我希望通过不依赖于id,该函数可以使用3、10或100个content_block div ...

有人能指出我正确的方向吗?

您可以通过将属性选择器与通配符开头为

$('[id^=content_block_button_').click(function () {
     $('[id^=content_block_textfield]').removeClass('highlight');
     id = "content_block_textfield_" + this.id.replace('content_block_button_', '');    
     $('#' + id).toggleClass('highlight');
     console.log(id);
});

暂无
暂无

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

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