2014-02-11 72 views
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的工作...

任何人都可以点我在正确的方向吗?

回答

0

您可以通过使用通配符开始的属性选择与

$('[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); 
}); 
缩短
相关问题