簡體   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