0
從數據源創建可變數量的div。裏面每個div都沒有作爲一個按鈕的圖像,以及包含文本等其它DIV雖然實際使用情況是較爲複雜的,我們可以用一個簡化的版本在這裏:jquery選擇除了調用函數之外的所有類的元素
<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類。這是一個非常unelegant和不易伸縮的功能,我想出了要處理這個問題:
//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");
});
我想我們都同意,這是不是很優雅,有效的代碼。並且它不能很好地擴展。
我想利用這個事實,即按鈕和textfield元素嵌套在同一個「父」。我想找到一種方法去除「從所有文本字段元素中刪除.highlight,除了」兄弟「按鈕元素調用該函數之外,我希望通過不依賴於id,該函數將會3,10或100 content_block div的工作...
任何人都可以點我在正確的方向嗎?