我有一个 DIV 列表,它们都包含一段文本、一个图像和一个锚点。
使用 Javascript/jQuery,是否可以获取锚点的 href,并使用该链接将图像包装在锚点标签中?
我知道这是一个奇怪的要求,我做了一个小提琴......
会有多个 div,所以我不能有相同的 id
我有一个 DIV 列表,它们都包含一段文本、一个图像和一个锚点。
使用 Javascript/jQuery,是否可以获取锚点的 href,并使用该链接将图像包装在锚点标签中?
我知道这是一个奇怪的要求,我做了一个小提琴......
会有多个 div,所以我不能有相同的 id
这是一种方法
var src = $("#imgid").attr("src"); //take out the src
$("#imgid").wrap($('<a href="'+src+'" />'); //wrap around it with the anchor
你的用法,可能是这样的
$("img", $("#divid")).each(function() {
var src = $(this).attr("src"); //take out the src
$(this).wrap($('<a href="'+src+'" />')); //wrap around it with the anchor
});
这是一个在你的小提琴上实现的演示。
尝试:
$('img').each(function(){
$(this).wrap('<a href="'+$(this).attr('src')+'"/>');
});
只是缩小那个img
选择器,也许有一个类。
如果我正确地得到了你想要的东西,你可以这样做:
$('a').attr('href', function() {
return $(this).find('img').attr('src');
});
正如你在这里看到的。
您应该将 .divs 之类的类添加到 div 和其他类以锚链接:
$(document).ready(function(){
$(".divs").each(function(){
$(this).find("a").hasClass("anchor").attr("href", $(this).find("a").hasClass("continue").attr('href'))
});
});
使用 jQuery:
$('.card-prod').each(function () {
var that = $(this),
imgA = that.find('a img').parent(),
newHref = that.find('a').not(imgA).attr('href');
imgA.attr('href', newHref);
});
好吧,让我们总结一下:
翻译成 jQuery:
$(".card-prod").each(function(){
var anchors = $(this).find("a");
anchors.eq(0).prop("href", anchors.eq(1).prop("href"));
});