【问题标题】:Jquery add and remove attribute on clickJquery在点击时添加和删除属性
【发布时间】:2015-09-17 11:20:52
【问题描述】:

希望我列出的项目在点击时添加一个 ID,我该怎么做?还是我做错了什么?

$('.ex-menuLi #tt').attr('id', 'test');
$('.ex-menuLi').on('click', function(){
    $(this).attr('id', 'test').siblings().removeAttr('id', 'test');
});
<nav id="extraMenu">
    <!--<ul id="ex-menuUl"> -->
    <li class="ex-menuLi" id="ex-menuLiId"><a href="#" class="test1" id="tt">Test</a></li>
    <li class="ex-menuLi" id="ex-menuLiId"><a href="#" class="test1">Test2</a></li>
    <li class="ex-menuLi" id="ex-menuLiId"><a href="#" class="test1">Test3</a></li>
<!--</ul>-->
</nav> 
#test{
    text-decoration:underline;
}

【问题讨论】:

  • ID 应该是唯一的。
  • 在课堂上做同样的事情,你就完成了你的工作
  • 您为什么要注释掉列表的开始和结束标记?如果没有这些标签,您的 HTML 将无效。还有“…else it will not work with my rest of my code”——那么你的其余代码需要修复,不要破坏一件事来解释其他地方的错误,正确/安全地完成它并且有效。

标签: javascript jquery html css


【解决方案1】:

//你可以这样设置uniqueid

$('.ex-menuLi').each(function(index){
   $(this).attr('id', index)
 });

【讨论】:

    猜你喜欢
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多