【问题标题】:jQuery get .text() but not the text in spanjQuery 获取 .text() 但不是 span 中的文本
【发布时间】:2011-08-20 06:14: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');

        });
    });
}

我想做的是在&lt;a 中但在&lt;span&gt; 之前获取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;
});;

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

【问题讨论】:

  • 我不清楚你在问什么。您是否正在寻找一种更好的方法来构建菜单的 html?或者在菜单已经构建后访问锚的标题?
  • 这里是一个示例
  • 消息4 a>
  • 当我单击该链接时会发生什么,当我希望它显示消息时它会显示以下消息4
  • 标签: javascript jquery menu textnode


    【解决方案1】:

    很好的解决方案 Herman,虽然它可以简化为这样的:

    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/

    【讨论】:

    • +1:这个更简洁的版本让我更容易理解解决方案
    【解决方案2】:

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

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

    【讨论】:

    • +1 赫尔曼,很好的解决方案。这是list of NodeTypes,任何想知道“3”是什么意思的人。
    • 我使用上面的一些代码修复了它。现在它看起来像这样并且可以工作,也许不是最干净的。 [code] $('ul#mainmenu li').live('click', function(event){ //alert(this.id); $("li#"+lastpageid).removeClass(); fetchpage(this .id); var text = ''; $('li#'+this.id+'a').contents().each(function(){ if(this.nodeType === 3){ text += this .wholeText; } }); $("#largemenutop").html(text); $("li#"+this.id).addClass("active"); lastpageid = this.id; }); [/code]
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签