jQuery 获取 .text() 但不获取 span 中的文本

jQuery get .text() but not the text in span

本文关键字:获取 span 文本 text jQuery      更新时间:2023-09-26

这是我的jQuery部分,它为我的页面制作菜单。

function fetchmenus() {
    $.getJSON('sys/classes/fetch.php?proccess=1', function(status) {
        // get line status
        $.each(status, function(i, item) {
            if (item.id == "1") {
                active = "class='active'";
                lastpageid = item.href;
            }
            else {
                active = "class='nonactive'";
            }
            $('<li id="' + item.href + '" ' + active + '><a href="#' + item.href + '">' + item.menuTitle + '<span class="menuspan" id="' + item.href + '"></span></a></li>').appendTo('#menuarea ul#mainmenu');
        });
    });
}

我想做的是在<a中但在<span>之前获得item.menuTitle

目前我是这样做的:

$('ul#mainmenu li').live('click', function(event) {
    //alert(this.id);
    $("li#" + lastpageid).removeClass();
    fetchpage(this.id);
    $("#largemenutop").html($(this).text());
    $("li#" + this.id).addClass("active");
    lastpageid = this.id;
});;

有没有更好的方法可以做到这一点?

很好的解决方案赫尔曼,尽管它可以简化为这样的东西:

.JS

$('li a').contents().filter(function() {
    return this.nodeType == 3;
}).text();

.HTML

<li><a href="#">Apple<span>hi</span> Juice</a></li>

会回来Apple Juice

小提琴:http://jsfiddle.net/49sHa/1/

是的,您只能选择元素的文本内容,如下所示:

 var text = '';
 $('a').contents().each(function(){
    if(this.nodeType === 3){
     text += this.wholeText;
    }
 });
 $("#largemenutop").html(text);