简体   繁体   English

jQuery:如何删除上一个元素?

[英]jquery: how to remove the previous element?

how do i remove a previous element to the triggering one with jquery? 如何使用jquery删除触发元素的前一个元素?

i have tried: 我努力了:

$(this).prev().remove();
$(this).next().remove();

but nothing works! 但是什么都行不通!

Be sure jQuery is properly referenced, and all of your syntax is correct: 确保正确引用了jQuery,并且所有语法均正确:

$("li").click(function(){
  $(this).prev().remove();
});

Works with: 适用于:

<ul>
  <li><p>Don't delete me!</p></li>
  <li><p>Click me to delete him!</p></li>
  <li><p>Click me twice, to take 'em both out!</p></li>
  <br/> <!-- line break added after OP's comments -->
  <li><p>Click me to remove the line-break!</p></li>
</ul>

Often when seemingly correct jQuery syntax doesn't work (especially with traversing) it is often because you are operating on the wrong element. 通常,当看似正确的jQuery语法不起作用(尤其是遍历时)时,通常是因为您对错误的元素进行了操作。 Take a look at this HTML: 看一下这个HTML:

<div>
  Please remove me
</div>
<div>
  <span>Click to remove</span>
</div>

Now, if we wired this up with a click event on the span it is important to first call parent() to get the containing div , and then get the previous element: 现在,如果我们通过span上的click事件进行连接,那么首先调用parent()以获取包含div ,然后获取上一个元素很重要:

$("span").click(function(){
    $(this).parent().prev().remove();
});

A simple call to $(this).prev().remove() would fail because the span is the only child of the div . $(this).prev().remove()的简单调用将失败,因为spandiv的唯一子级。

The exact code you posted works for me . 您发布的确切代码对我有用

Note that this is always set to an element in eg a jQuery click handler, but not in other JavaScript functions (unless you arrange for it to happen that way). 请注意, this总是在jQuery click handler中设置为一个元素,但在其他JavaScript函数中则不会设置(除非您安排它以这种方式发生)。

We'll be better able to answer your question if you provide a little more context. 如果您提供更多背景信息,我们将能够更好地回答您的问题。 Note that this won't necessarily point to the current element unless you are within the context of a handler. 请注意,除非您位于处理程序的上下文中,否则它不一定指向当前元素。 What are you trying to achieve here? 您想在这里实现什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM