简体   繁体   English

将代码添加到链接中指定的元素的动态代码

[英]Dynamic code to addClass to an element specified in the link

I'm trying to add a class to an element specified within my HTML from clicking on a button. 我试图通过单击按钮将类添加到HTML中指定的元素中。

HTML: HTML:

<div id="servicenext"><a href="#nav2"><p class="four">next</p></a>

Script: 脚本:

$('#servicenext a').click(function(){
     $('ul.navigation a').removeClass('active');
     $(*the div in the href*).addClass('active');
}); 

I'm hoping to have code that's dynamic. 我希望代码是动态的。 Basically it'll work by adding the class to any element specified in the a href. 基本上,可以通过将类添加到a href中指定的任何元素中来工作。 This is because i have quite a handful of these and do not wish to code them individually. 这是因为我有很多这些,并且不希望单独编码。

EDIT: 编辑:

Thanks James! 谢谢詹姆斯! that's great! 那很棒! But I do have to apologize, i was confused myself at what I was asking for! 但是我必须道歉,我对自己的要求感到困惑! What I'm actually looking to addClass to was actually the li in ul.navigation a 我实际上想要将addClassul.navigation ali

So if I'm thinking right, im trying to do this: 因此,如果我想的没错,我会尝试这样做:

  • by clicking onto the servicenext button, 通过单击服务下一步按钮,
  • the code gets the id of the div in the href 该代码在href获取divid
  • the addClass is applied to the li with the same href addClass应用于具有相同hrefli

I'm guessing there should be if else statements somewhere, forgive me, i'm not really a programmer. 我猜应该在某处是否有其他语句,请原谅我,我不是真正的程序员。

the gibberish i came up with is: 我想出的胡言乱语是:

$('#servicenext a').click(function(){
     $('ul.navigation a').removeClass('active');
     $($(this).attr("href").find($('ul.navigation li a').attr("href"))).addClass('active');
}); 
});

Since the value of the href attribute is already a valid ID selector, you can simply use the value of the attribute: 由于href属性的值已经是有效的ID选择器,因此您可以简单地使用该属性的值:

$($(this).attr("href")).addClass('active');

Note that you have to get the actual attribute value. 请注意,您必须获取实际的属性值。 The native DOM property returns an actual URL, not just the value of the attribute. 本机DOM属性返回实际URL,而不仅仅是该属性的值。

Here's a working example . 这是一个有效的例子

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

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