jQuery 如何增加div id值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15745193/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:43:39  来源:igfitidea点击:

How to increment div id value?

javascriptjqueryhtml

提问by Niths

I have got a task to set the menu as selected. For that I use dynamic id. So I want to increment it with respect to the selection

我有一个任务来将菜单设置为选定的。为此,我使用动态 ID。所以我想相对于选择增加它

My code is

我的代码是

<div class="menuHeader ui-corner-top" id="menu"+ i>
    <span><a href="#" onclick="Home()">Home</a></span>
</div>
<div class="menuHeader ui-corner-top" id="menu"+ i>
    <span><a href="#" onclick="NewTransaction()">New Transaction</a></span>
</div>
<div class="menuHeader ui-corner-top" id="menu"+ i>
    <span><a href="#" onclick="Portfolio()">Portfolio</a></span>
</div>

javascript is

javascript是

$(document).ready(function () {
             alert(document.URL);
             var list = $("#menu");
             for (var i = 1; i <= list.length; i++) {
                 list[i].innerHTML = i;
             }
             var str = document.URL.toLowerCase().indexOf("portfolio/index");
             alert(str);
             if (str >= 0) {
                 $('#menu').addClass("menuHeaderActive");
             }
         });

How can I do this?

我怎样才能做到这一点?

回答by writeToBhuwan

var i=0;
$('.menuHeader').each(function(){
    i++;
    var newID='menu'+i;
    $(this).attr('id',newID);
    $(this).val(i);
});

回答by Gumbo

This is the way to do it with Jquery

这是用 Jquery 做到的方法

val elementList = $(".menu");
for (var i = 1; i <= list.length; i++) {
    elementList[i].attr("id", "menu" + i);
}

回答by netadictos

Just use a class name instead of an id, you will be able to reuse the code you have just added but in this way.

只需使用类名而不是 id,您就可以以这种方式重用刚刚添加的代码。

 var list = $(".menu");

One advice, don't do the highlighting of the item menu with javascript, do it server-side, and you can add the "activating" class directly in the HTML of the LI.

一个建议,不要用javascript做项目菜单的高亮,在服务器端做,你可以直接在LI的HTML中添加“激活”类。