[英]jquery get href and text from a tags on a page and show them in a div
This is my jquery code: 这是我的jQuery代码:
$(document).ready(function() {
var contentText = $.ajax({
url: "index.php",
async: false
}).responseText;
$("#defaultData").append(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. 该代码的作用:获取页面(index.php)进行打印,删除图像并从所有a-tag获取href和文本。
1st question: text should give me: link and text but it gives me link and link :s I realy don't get this 第一个问题:文字应该给我:链接和文字,但是它给了我链接和链接:s我真的不明白这一点
2nd question: Alse I want to append the href and text to a div, seperated by semi colons. 第二个问题:另外,我想将href和文本附加到以半冒号分隔的div中。 So it looks like this: link;text link;text ...
所以看起来像这样:link; text link; text ...
Now I get: link link text text ... 现在我得到:链接链接文本文本...
I don't think that $('slector').each() is designed to return values. 我不认为$('slector')。each()旨在返回值。 You should populate a viariable inside the loop like this:
您应该像这样在循环内填充一个viariable:
var href = []
$('a').each(function() {
href.push($(this).attr('href'))
})
console.log(href)
This should give you all the link;text link;text
这应该给您所有
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 之所以以link; link; link然后是text; text ..结尾,是因为您正在通过以下方式处理所有链接
$.each(href, function(i, val) {
$("#data").append(i + " => " + val + "<br/>");
});
before even processing the texts. 甚至在处理文本之前。 Add them at the same time as shown above.
如上图所示,同时添加它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.