简体   繁体   English

HTML / Jquery:$('a')。attr('href')和.each?

[英]HTML/Jquery: $('a').attr('href') and .each?

My questions regards HTML and Jquery. 我的问题与HTML和Jquery有关。

I have some links in HTML code, something like this: 我在HTML代码中有一些链接,如下所示:

<a href="#box1">Item1</a>
<a href="#box2">Item2</a>
<a href="#box3">Item3</a>
etc.

In my current JQuery script, I have the following code: 在当前的JQuery脚本中,我具有以下代码:

$(function () {
    var targetbox = $('a').attr('href');
    $('a').click(function (event) {
        $(targetbox).fadeIn(2000);
        $('#showtext').text(targetbox);
    });
});

What this script does (or should do eventually) is fade in one of the hidden divs (#box1, #box2, etc) depending on what link (see HTML code) is clicked. 该脚本的作用(或最终应该做的)取决于所单击的链接(请参见HTML代码)在一个隐藏的div(#box1,#box2等)中淡入淡出。 I added the #showtext div to see of the attribute is being correctly stored. 我添加了#showtext div来查看属性是否正确存储。

The script works fine, however, only with the first href attribute that is found in the first link. 但是,该脚本只能与第一个链接中的第一个href属性一起使用。 I am aware that $('a').attr('href') grabs only the attribute of the first 'a' element and that I need to add .each somewhere, but I am lost as to where exactly to add this. 我知道$('a')。attr('href')仅获取第一个'a'元素的属性,我需要在每个地方添加.each,但是我不知道该在哪里添加它。 I tried adding in several places but it stopped the code working. 我尝试在几个地方添加,但是它停止了代码的工作。

Thank you for help. 谢谢你的帮助。

Gee e

Since the ID is contained in the href attribute and this is referring to the clicked element, you simply have to access its attribute: 由于ID包含在href属性, this是指点击的元素,你只需要访问它的属性:

$('a').click(function (event) {
    $(this.getAttribute('href')).fadeIn(2000);
    // or: $($(this).attr('href')).fadeIn(2000);
});
$(function(){
   $("a").click(function(e){
       e.preventDefault(); //avoid applying the hash to the browser (unless desired)
       var href = $(this).attr("href").split("#")[1]; //IE6 will append the URL in front of the hash
       $("#" + href).fadeIn(2000);
   });
});

Not that I have any experience with jQuery or anything (peronally I think it's for lazy programmers), but shouldn't you have something like: 并不是说我有使用jQuery或其他任何东西的经验(通常我认为这是为懒惰的程序员准备的),但是您不应该有类似的东西:

$(function(){ 
    $('a').click(function(event) { 
        var targetbox = $(this).attr('href'); 
        $(targetbox).fadeIn(2000); 
        $('#showtext').text(targetbox); 
    }); 
}); 

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

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