如何添加文本以跨越 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16426965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add text to span jQuery
提问by user1766952
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 a b c d e then all my menus e e e e e can any body help me thanks
菜单更改为最后一个值,例如,如果我的值是 abcde,那么我所有的菜单 eeeee 任何人都可以帮助我,谢谢
采纳答案by pala?н
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>');
}
回答by Kalecser
You can try using this to select only the last .down instead of all:
您可以尝试使用它来仅选择最后一个 .down 而不是全部:
$('.down:last').text(test);
回答by Karl-André Gagnon
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);
回答by writeToBhuwan
$('.down').each(function(){
$(this).text(test);
});
回答by carrabino
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". Then, you are modifying the class (i.e. all li's that have the class "down"). What you want is to assign a unique id to each li.
我假设您为每个菜单项多次调用 createList() ,但是此函数创建了一组具有相同类的 li,称为“down”。然后,您正在修改类(即所有具有“向下”类的 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");
});