开发者

jquery get href and text from a tags on a page and show them in a div

开发者 https://www.devze.com 2023-02-20 04:53 出处:网络
This is my jquery code: $(document).ready(function() { var contentText = $.ajax({ url: \"index.php\", async: false

This is my jquery code:

$(document).ready(function() {

var contentText = $.ajax({
    url: "index.php",
    async: false
}).responseText;

$("#defaultData").a开发者_高级运维ppend(contentText);

$('img').each(function(){
    $(this).remove();
});

//delegate?

var test =  0;  
var href = 0;
var title = 0;

$('.btn').click(function(){


    var href = $('a').each(function() {
        $(this).attr('href');
    });
    console.log(href);

    var test = $('a').each(function() {
        $(this).text();
    });

    console.log(test);

$.each(href, function(i, val) {
        $("#data").append(i + " => " + val + "<br/>");
    });

    $.each(test, function(i, val) {
        $("#data").append(i + " => " + val + "<br/>");
    });

}); 
//for (var i = 0; 50; i++) {    
//var pageNum = $("a#specificLink").attr("href").match(/page=([0-9]+)/)[1];
});

What this code does: It gets a page (index.php) prints it, removes the images and gets the href and text from all a-tags.

1st question: text should give me: link and text but it gives me link and link :s I realy don't get this

2nd question: Alse I want to append the href and text to a div, seperated by semi colons. So it looks like this: link;text link;text ...

Now I get: link link text text ...


This should give you all the link;text link;text

var test = "";
$('a').each(function() {
    test += $(this).attr('href') + ';';
    test += $(this).text() + ' ';
});
alert(test);

The reason you end up with link;link;link then text;text.. is because you are processing all links via

$.each(href, function(i, val) {
    $("#data").append(i + " => " + val + "<br/>");
});

before even processing the texts. Add them at the same time as shown above.


I don't think that $('slector').each() is designed to return values. You should populate a viariable inside the loop like this:

var href = []
$('a').each(function() {
    href.push($(this).attr('href'))
})
console.log(href)


Just to add, it appears that you're using .each the way that .map should be used:

var href = $('a').map(function() {
    return this.href + ';' + $(this).text();
}).get();
$("#data").append(href.join(' '));
0

精彩评论

暂无评论...
验证码 换一张
取 消