嗨,大家好,我有个问题。 如何在我的网页中点击div中的图片网址和标题?
这是文章的结构:
<article class="white-panel">
<img src="image url to grab" alt="">
<h4><a href="#">Title to grab</a></h4>
<p><a href="#"><span class="fa fa-whatsapp"></span> Onclick grab image and title with Jquery</a></p>
<p><a href="#"><span class="fa fa-facebook"></span> Auf Facebook teilen</a></p>
</article>
我需要在页面上的几个文章元素中使用它,但它们都有相同的结构。
答案 0 :(得分:2)
如果你在文章中所有imgs的src和alt之后,你可能想尝试这样的事情。
$('article').each(function(in,elem){
var img = elem.children('img').attr('src');
var title = elem.children('h4').text();
// Code that does something with them
})
答案 1 :(得分:1)
如果所有这些文章的结构相同,则以下内容应该有效:
$('article p:first-of-type a').click(function() {
// Get the parent article of the clicked link
var parentArticle = $(this).parents('article');
// Find the img src and h4 (title) text
console.log($(parentArticle).find('img').prop('src'));
console.log($(parentArticle).find('h4 a').text());
});
console.log()
只是为了查看值,您可以将它们存储在变量中以供进一步使用。
答案 2 :(得分:0)
没有jQuery版本以防万一。
var articleList = document.getElementsByClassName('white-panel');
var imageList = new Array();
Array.prototype.slice.call(articleList).forEach(function(value, index) {
imageList.push({
url: value.src,
title: value.title
});
});