在 jQuery 上获取 href 属性

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

Get href attribute on jQuery

jquerygethrefeachattr

提问by BILL

I have some table rows

我有一些表格行

<tr class="b_row">
    <td>
        <div class="cpt">
            <h2>
                <a href="/ref/ref/1.html">example</a>
            </h2>
        </div>
    </td>
</tr>

<!--more elements -->

<tr class="b_row">
    <td>
        <div class="cpt">
            <h2>
                <a href="/ref/two/23.html">example N</a>
            </h2>
        </div>
    </td>
</tr>

I need to get hyperlinks in attribute. I use this script

我需要在属性中获取超链接。我用这个脚本

function openAll()
{
    $("tr.b_row").each(function(){
    var a_href = $('div.cpt').find('h2 a').attr('href');
    alert ("Href is: " + a_href);
}

Problem: variable a_hrefis always / ref/ref/1.html

问题:变量a_href总是/ref/ref/1.html

回答by M. Hryszczyk

In loop you should refer to the current procceded element, so write:

在循环中,你应该引用当前的 procceded 元素,所以写:

var a_href = $(this).find('div.cpt h2 a').attr('href');

回答by Dennis

var a_href = $('div.cpt').find('h2 a').attr('href');

should be

应该

var a_href = $(this).find('div.cpt').find('h2 a').attr('href');

In the first line, your query searches the entire document. In the second, the query starts from your trelement and only gets the element underneath it. (You can combine the finds if you like, I left them separate to illustrate the point.)

在第一行,您的查询搜索整个文档。在第二种情况下,查询从您的tr元素开始,只获取它下面的元素。(find如果你愿意,你可以组合s,我把它们分开来说明这一点。)

回答by nachito

Very simply, use thisas the context: http://api.jquery.com/jQuery/#selector-context

很简单,this用作上下文:http: //api.jquery.com/jQuery/#selector-context

var a_href = $('div.cpt', this).find('h2 a').attr('href');

Which says, find 'div.cpt'only inside this

其中说,'div.cpt'只能在里面找到this

回答by Muhammad Usman

Use this:

用这个:

$(function(){
    $("tr.b_row").each(function(){
    var a_href = $(this).find('div.cpt h2 a').attr('href');
    alert ("Href is: "+a_href);

    });
});

See a working demo:http://jsfiddle.net/usmanhalalit/4Ea4k/1/

查看工作演示:http : //jsfiddle.net/usmanhalalit/4Ea4k/1/

回答by Mark Kahn

add a reference to this, which refers to your b_row:

添加对 的引用this,它指的是您的b_row

$("tr.b_row").each(function(){
    var a_href = $( this ).find('div.cpt h2 a').attr('href');
    alert ("Href is: "+a_href);
});

回答by Ariful Islam

Use $(this)for get the desire element.

使用$(this)了得到的欲望元素。

function openAll()
{
     $("tr.b_row").each(function(){
        var a_href = $(this).find('.cpt h2 a').attr('href');
        alert ("Href is: "+a_href);
     });
}