-1

请看下面的代码:

<!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>

JSFiddle 这里:http: //jsfiddle.net/VFGsU/

如果您看到上面的代码,那么在变量“bg”中,我正在获取li元素背景图像的 url。

我想在这个 url 上调用 jQuery 的 remove() 方法(即在变量 bg 上)......

实际上,我想实现这一点,当用户单击此背景图像时,li必须从ul.

如何做到这一点?

4

2 回答 2

0

更新了演示

HTML

li附上里面的文字span

<li><span>li (child) (grandchild)1</span></li>

js

$(function () {
    $("li").click(function () {
        var bg = $(this).css('background-image');
        bg = bg.replace('url(', '').replace(')', '');
        $(this).remove();
    });
    $('li span').click(function (e) {
        e.stopPropagation(); //if click on text no action
    });
});

演示

$(function () {
    $("li").click(function () {
        var bg = $(this).css('background-image');
        bg = bg.replace('url(', '').replace(')', '');
        alert(bg);
        $(this).remove(); //remove clicked li
    });
});
于 2013-08-12T15:04:19.990 回答
0

听起来您想查找他们是否碰巧单击了 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();
    }
}

如果需要,使您的 LI 位置:相对,和您的 .remove 类位置:绝对,并且您可以将关闭按钮放置在相对于 LI 标记的任何位置。

于 2013-08-12T15:21:25.390 回答