您能否伸出援助之手,因为我在获取标题文本和图像元素的来源以创建单击的项目列表时遇到了一些麻烦。但我会用一些代码更好地解释:
首先我有一个像这样的 div 元素:
<div class="main_page_entry">
<div class="main_item_desc">
<img class="main_item_pic" src="blah.jpg" />
<h6><a href="blah.html">Item Title</a></h6>
<span class="icon"> <img src="icon.png" /></span><br />
<span class="address">Some address</span>
<p class="item_desc">More blahs and links for description </p>
</div>
<div class="item_controls">
...
<a href="#" class="add_to_list">
<img src="add_icon.gif" />Add to List
</a>
...
</div>
</div>
它由一个包含两个较小的大 div 组成。我想要做的是:当我单击“添加到列表”链接时,我只想获取其中的文本和 main_item_pic 源,以便使用这两个项目创建一个列表项。
这是我迄今为止编写的代码:
$('a.add_to_list').live('click', function() {
var name = $(this).closest('h6').text();
var source = $(this).closest('.main_item_pic').src;
$('<li class="hide list_entry"><span class="entry_title">'+
name+'</span><button class="remove_entry"></button>'+
'<img class="list_entry" src="'+source+'" /></li>')
.appendTo('#favs_list ul')
.show('slow');
});
显然这是行不通的!我尝试过在这里读到的不同解决方案,例如:
var name = $(this).closest('h6').html();
var source = $(this).closest('.main_item_pic').attr('src');
但是哦好吧...到目前为止还没有运气。有任何想法吗?预先感谢!
最佳答案
尝试返回顶部,然后沿着右侧 DOM 分支再次向下:
var src = $(this).closest('.main_page_entry') // Back to the top
.find('.main_item_desc .main_item_pic') // And down again.
.attr('src');
closest
method通过你的祖先沿着 DOM 树向上:
Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
因此它不会跨越任何兄弟分支。然后,一旦到达适当的祖先,就可以使用 find
归根结底,find
就像 $()
但使用指定的元素而不是 document
作为根:
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
关于javascript - 如何使用 JQuery 从远程元素获取 img src 和文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6239170/