$.each()里面的再寻找只含text的子节点集问题。以下代码无报错,但hello无法变成world。<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function test(){
$.each($("a"),function(i,n){
//下面一行中的$(n+","+n+" *")不能相当于 $("a,a *")?
var only_text_nodes=$(n+","+n+" *").filter(function(i){$(this).children().length==0});
only_text_nodes.html("world");
$(n).attr("href","###");
});
alert($(".box").html());
}
</script><div class="box">
<a href="#">hello</a>
<a href="#"><span>hello</span></a>
<a href="#"><span><span>hello</span></span></a>
<a href="#"><span>hello1</span><span>hello2</span></a>
</div>
<button onclick="test();">test</button>

解决方案 »

  1.   

    <script type="text/javascript">
        function test(){
            $.each($("a"),function(i,n){
                //下面一行中的$(n+","+n+" *")不能相当于 $("a,a *")?
                //这里的 n代表$a对象,而不是字符串a所有
                var only_text_nodes=$(n+","+n+" *").filter(function(i){$(this).children().length==0});
                only_text_nodes.html("world");
                $(n).attr("href","###");
            });
            alert($(".box").html());
        }
    </script>
      

  2.   


    <script type="text/javascript">
        function test(){
    $('.box a').each(function(i,o){
    if($(o).children().length==0){
    $(o).html('world')
    }
    });
        }
    </script>
      

  3.   

    谢谢,但对这三行无效
    <a href="#"><span>hello</span></a>
    <a href="#"><span><span>hello</span></span></a>
    <a href="#"><span>hello1</span><span>hello2</span></a>
      

  4.   

    用nodeType判断类型 
    1-ELEMENT
    2-ATTRIBUTE
    3-TEXT
    4-CDATA
    5-ENTITY REFERENCE
    6-ENTITY
    7-PI (processing instruction)
    8-COMMENT
    9-DOCUMENT
    10-DOCUMENT TYPE
    11-DOCUMENT FRAGMENT
    12-NOTATION 
      

  5.   


    <script type="text/javascript">
    function test(){
    $('.box a').each(function(i,o){
    $(o).html($(o).html().replace(/hello/g,'world'))
    });
    }
    </script>……无语那……
    如果你要对所有都有用,你这段代码是干什么的?“$(this).children().length==0”
    专门写出来误导人的?
      

  6.   


    <a href="#"><span>hello</span></a>
    <a href="#"><span><span>hello</span></span></a>
    <a href="#"><span>hello1</span><span>hello2</span></a>这些也要变成
    <a href="#"><span>world</span></a>
    <a href="#"><span><span>world</span></span></a>
    <a href="#"><span>world</span><span>world</span></a>