将_top添加到特定div中的标记 - jQuery

时间:2012-02-27 21:41:49

标签: jquery html attr

我在几个嵌套的div标签中有几个标签,例如

<div id="top_level_div">
    <div id="inner_level_div">
        <a href="http://yahoo.com>text</a>
    </div>
    <div id="inner_level_div1>
        <a href="http://yahoo.com>text</a>
    </div>
</div>

我需要将目标属性添加到id为“top_level_div”的div中的所有标签。换句话说,“top_level_div”中的每个“A”标记都应该显示为

<a href="http://yahoo.com" target="_top">text</a>

“top_level_div”标签内可能有很多div标签,我无法控制它们出现的方式。

实现这个目标的最佳途径是什么?

编辑...

我尝试在&lt; / body&gt;之前的页面末尾添加以下代码标签,但它不起作用。

<script>
$(document).ready(function(){
    $('#xrx_bnr_hdr').find('a').attr('target', '_top');
    $('#xrx_bnr_ftr').find('a').attr('target', '_top');
});
</script>

6 个答案:

答案 0 :(得分:0)

像这样:

   $("#top_level_div a").attr("target","_top");

答案 1 :(得分:0)

#top_level_div a将为您提供ID = top_level_div的元素的所有锚标记后代:

$('#top_level_div a').attr('target', '_top');

答案 2 :(得分:0)

这样的事情怎么样:

$("#top_level_div a").attr("target","_top");

答案 3 :(得分:0)

//select the root element
//then find all the `a` elements that are descendants of the root element
//then change that set of elements `target` attribute to `_top`
$('#top_level_div').find('a').attr('target', '_top');

.attr()的文档:http://api.jquery.com/attr

答案 4 :(得分:0)

$("#top_level_div a").attr("target","_top")

答案 5 :(得分:0)

尝试,

$('#top_level_div').find('a').attr('target', '_top');

DEMO