Javascript 如何在背景图像上调用jQuery中的click事件?
请参阅以下代码:Javascript 如何在背景图像上调用jQuery中的click事件?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,请参阅以下代码: <!DOCTYPE html> <html> <head> <style> ul li { BACKGROUND: url('Close.png'); background-repeat: no-repeat; background-position: center;
<!DOCTYPE html>
<html>
<head>
<style>
ul li {
BACKGROUND: url('Close.png');
background-repeat: no-repeat;
background-position: center;
background-position: right;
background-color: orange;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(function() {
$("li").click(function() {
var bg = $(this).css('background-image');
bg = bg.replace('url(', '').replace(')', '');
alert(bg);
});
});
</script>
</head>
<body>
<div style="width:500px;">div (grandparent)
<ul>
<li>li (child) (grandchild)</li>
<li>li (child) (grandchild)</li>
<li>li (child) (grandchild)</li>
<li>li (child) (grandchild)</li>
<li>li (child) (grandchild)</li>
</ul>
</div>
</body>
</html>
ulli{
背景:url('Close.png');
背景重复:无重复;
背景位置:中心;
背景位置:右;
背景颜色:橙色;
}
$(函数(){
$(“li”)。单击(函数(){
var bg=$(this.css('background-image');
bg=bg.replace('url(','').replace('),'');
警报(bg);
});
});
分区(祖父母)
- 李(子)(孙)
- 李(子)(孙)
- 李(子)(孙)
- 李(子)(孙)
- 李(子)(孙)
请点击此处:
如果您看到上面的代码,那么在变量“bg”中,我将获得li
元素的背景图像的url
我想在此url(即变量bg)上调用jQuery的remove()方法
实际上,我想实现的是,当用户单击此背景图像时,特定的li
必须从ul
中删除
如何做到这一点
HTML
在span
<li><span>li (child) (grandchild)1</span></li>
听起来你想知道他们是否碰巧点击了LI中背景图像的“位置”…这比你只做一个子标记并检查子标记是否被点击要复杂得多…因为你必须测试鼠标位置等。但是,如果你在LI中有一个内标记…这相当容易。因此,我认为这是一个更好的方法:
CSS
li > .remove { display:inline-block;width:20px;height:20px;
background-image: close.png; }
HTML
<li data-toggle='remove'><span class='remove'></span></li>
JAVASCRIPT
$(document).on('click', '[data-toggle=remove]', function(e) {
var $clickedTag = $(e.target);
if( $clickedTag.hasClass('remove') ) {
$(this).remove();
}
}
CSS
移除{显示:内联块;宽度:20px;高度:20px;
背景图像:close.png;}
HTML
JAVASCRIPT
$(文档)。在('单击','[data toggle=remove]'上,函数(e){
变量$clickedTag=$(即目标);
如果($clickedTag.hasClass('remove')){
$(this.remove();
}
}
如果需要,请将LI位置设置为相对,将.remove类位置设置为绝对,然后可以将关闭按钮放置在相对于LI标记的任何位置。
$(this).css('background-image','')
“必须从ul中删除perticular li”。li
或背景图像
?添加了一个JSFIDLE,以便人们可以使用它。@putvande:我希望当用户单击背景图像时,该perticular li必须从ul中删除……如果用户单击li中的其他位置,则该li不应被删除ved…因此此li删除功能应仅绑定到背景图像单击。。。。。
$(function () {
$("li").click(function () {
var bg = $(this).css('background-image');
bg = bg.replace('url(', '').replace(')', '');
alert(bg);
$(this).remove(); //remove clicked li
});
});
CSS
li > .remove { display:inline-block;width:20px;height:20px;
background-image: close.png; }
HTML
<li data-toggle='remove'><span class='remove'></span></li>
JAVASCRIPT
$(document).on('click', '[data-toggle=remove]', function(e) {
var $clickedTag = $(e.target);
if( $clickedTag.hasClass('remove') ) {
$(this).remove();
}
}