jQuery 如何获取div内列表的所有链接?

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

How to get all the links of a list inside a div?

jqueryhtmldom

提问by Miles M.

I have a code with the following DOM Tree:

我有一个包含以下 DOM 树的代码:

<div id="blogPagination">
    <div class="pagination">
        <ul>
            <li>
                <a href="/2" >1</a>
            </li>
            <li>
                <a href="/3" >2</a>
            </li>
        </ul>
    </div>
</div>

I'm trying to reach the href of my tag. I can't reach it with anything I tried.

我正在尝试访问我的标签的 href。我尝试过的任何东西都无法达到它。

What's the best way to reach it with jQuery ?

使用 jQuery 达到它的最佳方法是什么?

I tried:

我试过:

console.log($('#blogPagination div ul > li a ').attr("href"));

console.log($('#blogPagination > a ').attr("href"));

$('#blogPagination').children('a')

console.log($('#blogPagination div ul li a').attr("href"));

console.log($('#blogPagination div ul > li a ').attr("href"));

console.log($('#blogPagination > a ').attr("href"));

$('#blogPagination').children('a')

console.log($('#blogPagination div ul li a').attr("href"));

without luck ..

没有运气..

Thanks

谢谢

EDIT:

编辑:

After nbrooks's answer, here is what I tried so far:

在 nbrooks 的回答之后,这是我迄今为止尝试过的:

function bindPagination() {

    console.log("bind");

    $(function() {
        var links = $("#blogPagination ul a").map(function(e) {
        e.preventDefault();
            return this.href;
        }).get();
        console.log(links);
});

EDIT 2 :

编辑 2:

Considering Syfaro's answer, I've also tried :

考虑到 Syfaro 的回答,我也尝试过:

$('#blogPagination').find('a').each(function(e) {
    e.preventDefault();
    console.log($(this).attr('href'));
});

Without luck.

没有运气。

EDIT 3 : I'd like to give more details concerning this function that may have a significant impact after all:

编辑 3 :我想提供有关此功能的更多详细信息,毕竟可能会产生重大影响:

to load this pagination, I'm using Ajax and handlebars wrapped into a document ready function:

要加载此分页,我使用 Ajax 和包含在文档就绪函数中的把手:

$(document).ready(function(){

    // Get the customer service stats
    var Content = {

    init: function() {

            /* this.getHomePosts(); */
            this.getBlogPosts();
        },

    getBlogPosts: function(offset) {
        if(offset == undefined){
            offset = 0;
        }
        // GET the events with JSON
        $.ajax({
            type: "POST",
            data: {},
            url: site_url+"/main/blog/"+offset,
            dataType: "json",
            success: function(results) {
                posts = results["posts"].map(function (blogContent) {
                    if( blogContent.picture != '' ) {
                        return {
                            Title: blogContent.title ,
                            Picture: Content.urlPostPic + blogContent.picture ,
                            Video: '' ,
                            Text: blogContent.text ,
                            Datetime: blogContent.datetime ,
                        }
                    } else {
                        return {
                            Title: blogContent.title ,
                            Picture: '' ,
                            Video: blogContent.video ,
                            Text: blogContent.text ,
                            Datetime: blogContent.datetime ,
                        }
                    }
                });

                pagination = {pagination: results["pagination"]};

                var template = Handlebars.compile( $('#templateBlog').html() );
                $('#blogPosts').append( template(posts) );

                var template = Handlebars.compile( $('#templatePagi').html() );
                $('#blogPagination').append( template(pagination) );
                                    // Here we call bindPagination <===
                bindPagination();
            }
        });
    },

};

Content.init();

You can see in the get BlogPosts function that I call BindPagination which is supposed to be this function, to prevent default behavior and call the content depending of the offset (pagination system)

您可以在 get BlogPosts 函数中看到我调用 BindPagination 应该是这个函数,以防止默认行为并根据偏移量调用内容(分页系统)

function bindPagination() {

    console.log("bind");


    var links = $("#blogPagination ul a").map(function(e) {
        e.preventDefault();
        return this.href;
    }).get();
    console.log(links);

    $('#blogPagination').find('a').each(function(e) {
        console.log("clicked !");
        e.preventDefault();
        console.log($(this).attr('href'));

     //    var attr = this.attr();
        // var id = attr.replace("/","");

        // $('#blogPosts').empty();
        // $('#blogPagination').empty();
        // Content.getBlogPosts(id);
    });
}
});

the last }); stand for the end of the document ready.

最后 }); 站在文件的末尾准备好。

回答by ixchi

$('#blogPagination').find('a').attr('href');

This should find all aelements in the specified area, the get the hrefof them, assuming that you've already got jQuery and all that good stuff set up.

这应该找到a指定区域中的所有元素,获取href它们,假设您已经设置了 jQuery 和所有这些好东西。

If you have multiple aelements, you could do something like this:

如果您有多个a元素,则可以执行以下操作:

$('#blogPagination').find('a').each(function() {
    console.log($(this).attr('href'));
});

This will print out each hrefof each ain that div.

这将打印出那个中href的每一个。adiv

If you need to prevent the link from changing the page, you need to add a click handler to the aelements.

如果需要防止链接更改页面,则需要向a元素添加点击处理程序。

$('#blogPagination').on('click', 'a', function(e) {
    e.preventDefault();
    console.log($(this).attr('href'));
});

This will prevent the user from being taken to the link, and get the hrefof the link when clicked.

这将防止用户被带到链接,并href在单击时获取链接。

Is this what you want?

这是你想要的吗?

回答by nbrooks

The function you are likely looking for is map. This allows you to take a given jQuery collection and transform it by taking a specific property of each object and making that the element in the resulting collection.

您可能正在寻找的功能是map. 这允许您获取给定的 jQuery 集合并通过获取每个对象的特定属性并将其作为结果集合中的元素来转换它。

To collect all the href's in your array:

要收集数组中的所有 href :

$(function() {
    var links = $("#blogPagination ul a").map(function() {
        return this.href;
    }).get();
    console.log(links);
});

jsFiddle Demo

jsFiddle 演示

Note:The child selector(el1 > el2) only works when el2is, well, a direct descendant of el1. So at least one of your examples would have failed because you didn't match that with your DOM tree. However, console.log($('#blogPagination div ul > li a ').attr("href"));would work to find the href of (only) the very first anchor tag, assuming you wrapped it in a DOM-ready handler $(function() { ... });.

注:子选择器el1 > el2),只有当工作el2是,好了,直接后裔el1。所以至少你的一个例子会失败,因为你没有将它与你的 DOM 树匹配。但是,console.log($('#blogPagination div ul > li a ').attr("href"));假设您将其包装在 DOM-ready handler 中,则可以找到(仅)第一个锚标记的 href $(function() { ... });

The childrenmethod is similar, in that it will only find direct descendants (children), and not grandchildren, etc. If you want to find alldescendants down the DOM tree of a particular element, use findinstead.

children方法类似,因为它只会找到直接后代(子项),而不是孙子项等。如果要查找特定元素的 DOM 树中的所有后代,请find改用。

回答by andy

Check your console - as I suspect there is either a conflict or javascript error that is causing the jQuery not to work.

检查您的控制台 - 因为我怀疑存在导致 jQuery 无法工作的冲突或 javascript 错误。

Your statements are correct and should select the element you require.

您的陈述是正确的,应该选择您需要的元素。