jQuery 获取 .text() 但不是跨度中的文本 [英] jQuery get .text() but not the text in span

查看:18
本文介绍了jQuery 获取 .text() 但不是跨度中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

function fetchmenus() {$.getJSON('sys/classes/fetch.php?proccess=1', function(status) {//获取线路状态$.each(status, function(i, item) {如果(item.id ==1"){active = "class='active'";lastpageid = item.href;}别的 {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#主菜单');});});}

我想要做的是在 中但在 之前获取 item.menuTitle.>

目前我是这样做的:

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

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

解决方案

是的,你可以只选择元素的文本内容,像这样:

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

This is my jQuery part that makes my menu for my pages.

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');

        });
    });
}

What I want to do is get the item.menuTitle in the <a but before the <span>.

Currently I do it on this way:

$('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;
});;

Is there a better way to do this?

解决方案

Yes, you can select only the text contents of the element, like this:

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

这篇关于jQuery 获取 .text() 但不是跨度中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆