jQuery删除(选择器)似乎不起作用

时间:2013-04-18 11:15:49

标签: jquery

我创建了一个小jsfiddle: http://jsfiddle.net/duRXc/

<div data-role="wrapper">
    <span class="to-be-removed" data-role="to-be-removed">
        text to be removed
    </span>
</div>
<button id="remove1">Remove by jQuery object</button><br>
<button id="remove2">Remove by selector</button><br>
<button id="remove3">Remove by selector(class)</button>

var $wrapper = $('[data-role="wrapper"]');

$('#remove1').on('click', function () {
    $wrapper.find('[data-role="to-be-removed"]').remove();
});

// this should work: http://api.jquery.com/remove/
$('#remove2').on('click', function () {
    $wrapper.remove('[data-role="to-be-removed"]');
});

// this should work: http://api.jquery.com/remove/
$('#remove3').on('click', function () {
    $wrapper.remove('.to-be-removed');
});

我遇到的问题是.remove(选择器)重载不起作用。我认为它与我的数据角色选择器有关,但是按类选择器删除也不起作用。

我做错了吗?或者这是jQuery中的错误还是文档错误:

  

我们还可以将选择器包含为可选参数

http://api.jquery.com/remove/

4 个答案:

答案 0 :(得分:5)

$wrapper.find('span').remove('[data-role="to-be-removed"]')

相同

$wrapper.find('span').filter('[data-role="to-be-removed"]').remove()

var $wrapper = $('[data-role="wrapper"]');

$('#remove1').on('click', function () {
    $wrapper.find('[data-role="to-be-removed"]').remove();
});

// this should work: http://api.jquery.com/remove/
$('#remove2').on('click', function () {
    $wrapper.find('[data-role="to-be-removed"]').remove('[data-role="to-be-removed"]');
});

// this should work: http://api.jquery.com/remove/
$('#remove3').on('click', function () {
    $wrapper.find('[data-role="to-be-removed"]').remove('.to-be-removed');
});

http://jsfiddle.net/duRXc/3/

答案 1 :(得分:3)

要删除与您可以使用的选择器匹配的子元素:

$('[data-role="to-be-removed"]', $wrapper).remove();

remove(selector)方法是进一步过滤现有选择。例如......

<ul id="test">
    <li>One</li>
    <li class="example">Two</li>
    <li>Three</li>
</ul>

如果我选择了所有列表项,我可以删除与我的过滤器匹配的任何列表项:

$('#test li').remove('.example');

running example of this on JSFiddle

答案 2 :(得分:1)

$(selector).remove(filter)删除filter中所有匹配的$(selector)元素,请参阅此示例

http://jsfiddle.net/steelywing/duRXc/6/

答案 3 :(得分:0)

选择器仅支持包装器对象中的元素。 因此,如果您使用div而不是内部的span并选择所有div作为包装它可以工作。

e.g。 http://jsfiddle.net/hsLLr/

<div data-role="wrapper">
    <div class="to-be-removed" data-role="to-be-removed">
        text to be removed
    </div>
</div>
<button id="remove1">Remove by jQuery object</button><br>
<button id="remove2">Remove by selector</button><br>
<button id="remove3">Remove by selector(class)</button>

var $wrapper = $('div');

$('#remove1').on('click', function () {
    $wrapper.find('[data-role="to-be-removed"]').remove();
});

// this should work: http://api.jquery.com/remove/
$('#remove2').on('click', function () {
    $wrapper.remove('[data-role="to-be-removed"]');
});

// this should work: http://api.jquery.com/remove/
$('#remove3').on('click', function () {
    $wrapper.remove('.to-be-removed');
});