我在html页面的底部出现了一些搜索结果,我想抓住这些结果中出现的每个 li
元素的一些内容:
<ul id="hits">
<li class="hit">
<a href="#" class="image" style="background-image: url('http://...')"></a>
<div class="anotherclass">
<h5 class="title"> Here is a title </h5>
<p> Here is some paragraph text </p>
</div>
</li>
<li>...</li>
</ul>
我需要每个 li
的这两个元素(以此顺序):
-
h5
标签内的文字(即"这是标题"), - 和图像路径在锚点
a
标签内显示为属性(即background-image: url()
)
到目前为止,这一直是我的解决方案,但没有运气:
$(".hit").each(function() {
let title = $(this).find("title").innerHTML;
let img = $(this).find("image").attr("style");
});
我也不确定如何将style
属性内部的URL获取,但这也许是另一个问题。
$(".hit").each(function() {
let title = $(this).find(".title").text();
let img = $(this).find(".image").css('background-image');
});
我认为您的意思是使用课程。
首先您缺少.
,应该是.find(".title")
,.find(".image")
第二次从h5
获取文本使用.text()
而不是innerHTML
演示
$(".hit").each(function() {
let title = $(this).find(".title").text();
console.log(title)
let img = $(this).find(".image").attr("style");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="hits">
<li class="hit">
<a href="#" class="image" style="background-image: url('http://...')"></a>
<div class="anotherclass">
<h5 class="title"> Here is a title </h5>
<p> Here is some paragraph text </p>
</div>
</li>
<li>...</li>
</ul>
您的解决方案足够接近。由于title
和image
是类,因此您需要添加.
。其次,要获得h5
,您应该使用text()
而不是innerHTML
:
$(".hit").each(function() {
let title = $(this).find(".title").text();
let img = $(this).find(".image").attr("style");
console.log(title)
console.log(img)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="hits">
<li class="hit">
<a href="#" class="image" style="background-image: url('http://...')"></a>
<div class="anotherclass">
<h5 class="title"> Here is a title </h5>
<p> Here is some paragraph text </p>
</div>
</li>
</ul>
演示:https://jsfiddle.net/sxc3jad4/
如果要选择class
,则需要添加dot(.)
- 更改查找(" title")以查找("。标题")//找到具有标题类的元素
- 将innerhtml更改为text()//获取文本。
- 更改查找("图像")以查找("。image")//找到具有图像类的元素
- 将attr(" style")更改为css("背景图像")//获取属性背景图像的CSS值