jquery遍历和文本替换

时间:2016-02-29 10:54:43

标签: javascript jquery dom jquery-traversing

给出以下html代码

<div id="block_16" class="Block shadow">
  <div class="BlockControls">
    <div class="DeleteAction BlockAction"></div>
    <div class="BlockTitle BlockAction">Department File Maintenance</div>
    <div class="BlockTitleField BlockAction"></div>
    <div class="HelpAction BlockAction"></div>
    <div class="Separator">&nbsp;</div>
  </div>
  <div class="BlockObject">
    <div class="Filter" id="16_cbos_departments_table_filter_"></div>
    <div class="BlockNotices"></div>
  </div>
</div>


<div id="block_17" class="Block shadow">
  <div class="BlockControls">
    <div class="DeleteAction BlockAction"></div>
    <div class="BlockTitle BlockAction">Department File Maintenance</div>
    <div class="BlockTitleField BlockAction"></div>
    <div class="HelpAction BlockAction"></div>
    <div class="Separator">&nbsp;</div>
  </div>
  <div class="BlockObject">
    <div class="Process" id="17_cbos_departments_table_process_"></div>
    <div class="BlockNotices"></div>
  </div>
</div>

我希望将“部门文件维护”文本更改为“部门文件搜索”,但前提是div.BlockObject包含div.Filter。

我试过了

$('div.Filter').parent().sibling('div.BlockControl').child('div.BlockTitle').text().replace('Maintenance', 'Search');

$('div.Filter').closest('div.Block').find('div.BlockTitle').text().replace('Maintenance', 'Search');

两者都不起作用。

遍历DOM以获得所需结果的正确/最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

试试这个

$('.Filter').each(function() {
  $(this).closest('.Block').find('.BlockTitle').text('Department File Search');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block_16" class="Block shadow">
  <div class="BlockControls">
    <div class="DeleteAction BlockAction"></div>
    <div class="BlockTitle BlockAction">Department File Maintenance</div>
    <div class="BlockTitleField BlockAction"></div>
    <div class="HelpAction BlockAction"></div>
    <div class="Separator">&nbsp;</div>
  </div>
  <div class="BlockObject">
    <div class="Filter" id="16_cbos_departments_table_filter_"></div>
    <div class="BlockNotices"></div>
  </div>
</div>


<div id="block_17" class="Block shadow">
  <div class="BlockControls">
    <div class="DeleteAction BlockAction"></div>
    <div class="BlockTitle BlockAction">Department File Maintenance</div>
    <div class="BlockTitleField BlockAction"></div>
    <div class="HelpAction BlockAction"></div>
    <div class="Separator">&nbsp;</div>
  </div>
  <div class="BlockObject">
    <div class="Process" id="17_cbos_departments_table_process_"></div>
    <div class="BlockNotices"></div>
  </div>
</div>

答案 1 :(得分:0)

<script>

$(document).ready(function() {
$('.Block.shadow').each(function(){
  if($(this).find('div.BlockObject .filter')){
    $(this).find('.BlockTitle').html('Department File Search'); 
  }
});

});
</script>