如何在div中获取列表的所有链接?

时间:2022-04-27 16:00:46

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"));

控制台。日志($('#blogPagination div ul > li a ').attr("href"));

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

控制台。日志($(“# blogPagination >”).attr(“href”));

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

$(' # blogPagination ')定格(' a ')

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

控制台。日志($('#blogPagination div ul li a').attr("href"));

without luck ..

没有运气. .

Thanks

谢谢

EDIT:

编辑:

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

在n*s的回答之后,下面是我到目前为止所尝试的:

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和handlebars包装在一个文档准备函数中:

$(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.

最后});准备好文件的结尾。

3 个解决方案

#1


39  

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

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

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

If you have multiple a elements, you could do something like this:

如果你有多个a元素,你可以这样做:

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

This will print out each href of each a in that div.

这将打印出该div中每个a的href。

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

如果需要阻止链接更改页面,则需要向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 href of the link when clicked.

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

Is this what you want?

这就是你想要的吗?

#2


7  

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 el2 is, 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树匹配起来。然而,控制台。日志($('#blogPagination div ul > li a ').attr("href"));假设您将它封装在一个适合dom的处理程序$(function(){…});。

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

children方法是类似的,因为它只会找到直接的后代(子),而不会找到孙辈等等。

#3


0  

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

检查您的控制台——正如我所怀疑的那样,有冲突或javascript错误导致jQuery无法工作。

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

您的语句是正确的,应该选择所需的元素。

#1


39  

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

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

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

If you have multiple a elements, you could do something like this:

如果你有多个a元素,你可以这样做:

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

This will print out each href of each a in that div.

这将打印出该div中每个a的href。

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

如果需要阻止链接更改页面,则需要向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 href of the link when clicked.

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

Is this what you want?

这就是你想要的吗?

#2


7  

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 el2 is, 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树匹配起来。然而,控制台。日志($('#blogPagination div ul > li a ').attr("href"));假设您将它封装在一个适合dom的处理程序$(function(){…});。

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

children方法是类似的,因为它只会找到直接的后代(子),而不会找到孙辈等等。

#3


0  

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

检查您的控制台——正如我所怀疑的那样,有冲突或javascript错误导致jQuery无法工作。

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

您的语句是正确的,应该选择所需的元素。