我想删除未命名未分类 <div>
内的所有背景图像通过 url 使用 javascript 获取网页?
这些图像的实际 html 标签如下:
<div style="position:absolute;width:150px;height:150px;top:0px;
background:url(img-150x150.png) no-repeat left top;"></div>
我正在尝试的是以下内容:
$('*').filter(function () {
return $(this).css('background-image') == 'url("img150x150.png")'
}).remove();
但这不起作用。
最佳答案
你可以检查background-image
字符串中是否存在img-150x150.png
,因为它包含带有图像绝对路径的url..
$(document).ready(function() {
//this is if you want to remove those divs
$('body>div').filter(function() {
return $(this).css("background-image").indexOf("img-150x150.png") != -1
}).remove()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div style="width:150px;height:150px;top:0px;
background:url('img-150x150.png') no-repeat left top;"></div>
<div style="width:150px;height:150px;top:0px;
background:url('img-150x150.png') no-repeat left top;"></div>
<div style="width:150px;height:150px;top:0px;
background:url('img-150x150.png') no-repeat left top;"></div>
<div style="background:yellow;width:150px;height:150px;top:0px;"></div>
</body>
$(document).ready(function() {
//this is if you want to change background color of those divs
$('body>div').filter(function() {
return $(this).css("background-image").indexOf("img-150x150.png") != -1
}).each(function(){$(this).css("background","red");})
});
div{
margin:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div style="width:50px;height:50px;top:0px;
background:url('img-150x150.png') no-repeat left top;"></div>
<div style="width:50px;height:50px;top:0px;
background:url('img-150x150.png') no-repeat left top;"></div>
<div style="width:50px;height:50px;top:0px;
background:url('img-150x150.png') no-repeat left top;"></div>
<div style="background:yellow;width:50px;height:50px;top:0px;"></div>
</body>
由于 IE 7,8 不支持 indexOf
,这里是一个 polyfill:
Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) {
var a;
if (null == this) throw new TypeError('"this" is null or not defined');
var c = Object(this),
b = c.length >>> 0;
if (0 === b) return -1;
a = +e || 0;
Infinity === Math.abs(a) && (a = 0);
if (a >= b) return -1;
for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0); a < b;) {
if (a in c && c[a] === d) return a;
a++
}
return -1
});
关于javascript - 如何在 jquery/javascript 中删除给定 url 的所有 <div> 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38808032/