我有一个带有几个导航链接的导航。我必须为导航链接分配一个ID以使用特定的脚本。不幸的是我不能在脚本中使用类。用jQuery点击或添加和删除元素的ID
为该元素设置新的ID工作正常,脚本拿起事件并完成其工作。点击页面上的其他链接或其他导航链接后,将原始ID恢复到导航链接也可以使用,但我不确定这是否正确。
我的代码似乎只给点击的时间(什么是可取的)给新元素的ID然而我想知道如何可以切换或添加和删除新的ID,只有一次我点击任何其他链接(包括导航链接)。不知道是否仅在点击时使用元素上的新ID是件好事。
https://stackoverflow.com/questions/11489037/add-and-remove-attribute-with-jquery/11489050#11489050
和
https://stackoverflow.com/questions/7077673/add-and-remove-class-on-click/7077753#7077753
和
https://stackoverflow.com/questions/15418219/add-an-id-to-clicked-links-but-remove-it-from-others/15418623#15418623 非常接近我想要实现但这些问题不是支持类或单独的按钮。
HTML
<nav>
<ul>
<li><a class="navlink" id="Work" href="#Work">Work</a></li>
<li><a class="navlink" id="Portfolio" href="#Portfolio">Portfolio</a></li>
<li><a class="navlink" id="Print" href="#Print">Print</a></li>
<li><a class="navlink" id="Services" href="#Services">Services</a></li>
<li><a class="navlink" id="Contact" href="#Contact">Contact</a></li>
</ul>
</nav>
jQuery的
// bind event handler to element/s
$('.navlink').stop(true).click(function (e) {
// prevent default action
e.preventDefault();
// get the id of the clicked element
var currentId = $(this).attr('id');
// show alert with the id of the clicked element
alert("The current ID of the clicked element is "+ currentId +" ");
// change id of the element to newId
{this.id = "newId";}
// run script on clicked element
$(this).scrolld();
// give element back its original id it had before click
// not sure if this is ok
// it does work but I think there is better or more elegant ways
{this.id = currentId;}
// instead of {this.id = currentId;} I am trying to do something like this
// but it does not seem to work
// I would like the new id to stay with the element until any other link
// on the page is clicked and not only for the duration of the click
$('.navlink').click(function(){
$('.navlink').removeAttr("id")
$(this).attr("id", currentId);
});
});
什么是正确的做法会这样的代码,真正的元素被赋予新的ID一次点击,还给其原一旦页面上的任何其他元素被点击一次的ID?
我不确定是否在点击时使元素上的新ID以正确的方式完成,或者至少可以接受。
它的工作原理,但我不确定,似乎太简单了,如果你能帮助我想出一个更好或更稳固的方式,请提前分享你的想法和感谢。
问候