简体   繁体   English

如何添加文本以跨越jQuery

[英]how to add text to span jQuery

I have this jQuery code that I am using to create a dynamic menu 我有这个jQuery代码,我用来创建一个动态菜单

function createList(test){
      alert(test);
        $('#nav')
        .append('<li class="top"><a href="nogo2" id="products" class="top_link"><span class="down"></span></a></li>');
        $('.down').text(test);
    }

the problem that I have is when I try to add the text to the span 我遇到的问题是当我尝试将文本添加到跨度时

$('.down').text(test);

the menu changes to whatever value is the last for example if my values are abcde then all my menus eeeee can any body help me thanks 如果我的值是abcde,则菜单会更改为最后一个值,然后我的所有菜单eeeee都可以帮助我

您可以尝试使用此选项仅选择最后一个.down而不是全部:

$('.down:last').text(test);

Why don't you do it directly like this: 你为什么不直接这样做:

 function createList(test) {
     alert(test);
     $('#nav')
         .append('<li class="top"><a href="nogo2" id="products" class="top_link"><span class="down">' + test + '</span></a></li>');
 }

The selector $('.down') select every elements with the class down 选择器$('.down')选择与每一类元素down

If you want to select the last created .down use this : 如果要选择上次创建的.down使用以下命令:

$('.down:last').text(test);
$('.down').each(function(){
    $(this).text(test);
});

i assume that you're calling createList() multiple times for each menu item, but this function creates a group of li's with the same class called "down". 我假设你为每个菜单项多次调用createList(),但是这个函数创建了一组具有相同类的li,称为“down”。 Then, you are modifying the class (ie all li's that have the class "down"). 然后,您正在修改该类(即所有具有“向下”类的li)。 What you want is to assign a unique id to each li. 你想要的是为每个li分配一个唯一的id。

here is the fiddle solution: 这是小提琴解决方案:
http://jsfiddle.net/acturbo/vZAee/2/ http://jsfiddle.net/acturbo/vZAee/2/

this should work: 这应该工作:

function createList(test){
      //alert(test);
    var id = "product-" + test;
    console.log(test)

        $('#nav')
        .append('<li class="top"><a href="nogo2" id="products" class="top_link"><span id="'+ id +'"></span></a></li>');
        $("#"+id).text(test);
    }


$().ready(function() {
    createList( "a");    
    createList( "b");   
    createList( "c");   
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM