jQuery是一个快速、简洁的JavaScript库,它简化了HTML文档遍历、事件处理、动画和Ajax交互等操作。获取HTML文档中的链接值是jQuery常见的DOM操作之一。
// 获取文档中所有<a>标签的href属性值
$('a').each(function() {
var linkValue = $(this).attr('href');
console.log(linkValue);
});
// 获取id为"nav"的元素内所有链接
$('#nav a').each(function() {
console.log($(this).attr('href'));
});
// 获取类名为"external-link"的所有链接
$('a.external-link').each(function() {
console.log($(this).attr('href'));
});
// 同时获取链接文本和href值
$('a').each(function() {
var linkText = $(this).text();
var linkHref = $(this).attr('href');
console.log('文本: ' + linkText + ', 链接: ' + linkHref);
});
// 获取所有以"https://"开头的链接
$('a[href^="https://"]').each(function() {
console.log($(this).attr('href'));
});
原因:如果链接是通过Ajax或JavaScript动态加载的,在DOM加载完成时这些元素还不存在。
解决方案:
$(document).on('click', 'a', function() {
console.log($(this).attr('href'));
});
原因:获取的链接可能是相对路径,需要转换为绝对路径。
解决方案:
$('a').each(function() {
var absoluteUrl = new URL($(this).attr('href'), window.location.href).href;
console.log(absoluteUrl);
});
原因:页面中可能有多个相同链接。
解决方案:
var uniqueLinks = {};
$('a').each(function() {
var href = $(this).attr('href');
if (!uniqueLinks[href]) {
uniqueLinks[href] = true;
console.log(href);
}
});
没有搜到相关的文章