jQuery - 删除ID不起作用

时间:2015-12-09 18:21:24

标签: jquery

我试图这样做,当你点击一个元素时,它会删除所有带有该ID的元素(具有正确的onclick)



function reply_click(clicked_id)
{
	$("#" + clicked_id).remove();
	$(clicked_id).remove();
    alert(clicked_id + "Removed");
}

<span id="relate1" onClick="reply_click(this.id)">Some text to remove 1</span>
Some info to keep
<span id="relate1" onClick="reply_click(this.id)">Some text to remove 1</span>
Some info to keep
<span id="relate2" onClick="reply_click(this.id)">Some text to remove 2</span>
&#13;
&#13;
&#13;

我尝试了(&#34;#&#34; + clicked_id)和(clicked_id),以防万一我做错了。

这个想法是,如果有人点击带有id&#34; span1&#34;所有的related1 id都将被删除。但是,按&#34; related2&#34;其他一切都应该留下来。

5 个答案:

答案 0 :(得分:0)

要删除带有ID的垃圾邮件(当然,ID必须是唯一的):

&#13;
&#13;
curPID = feature('getpid');
syscall = sprintf('taskkill /F /FI "PID ne %u" /IM matlab.EXE', curPID);
system(syscall);
&#13;
function reply_click(clicked_id)
{
  $("span[id='" + clicked_id + "']").remove();
  // $('span[class*="' + clicked_id + '"]').remove(); // to remove by class
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您不应该为多个元素使用相同的ID作为uniuq属性。您可以使用class属性而不是ID。您可以通过$('。'+ className).remove();

删除节点

答案 2 :(得分:0)

id必须是唯一的。您可以在不使用id之类的情况下执行此操作。

&#13;
&#13;
function reply_click(clicked_id)
{
    $(clicked_id).remove();
    alert(clicked_id.id + " Removed");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="relate1" onclick="reply_click(this)">Some text to remove 1</span>
Some info to keep
<span id="relate2" onclick="reply_click(this)">Some text to remove 1</span>
Some info to keep
<span id="relate3" onclick="reply_click(this)">Some text to remove 2</span>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

所有答案和评论都说Ids必须是唯一的

你可以简单地使用

function reply_click(clicked_Element)
{
    clicked_Element.remove();
    alert("clicked_Element Removed");
}

和html

<span id="relate1" onClick="reply_click(this)">Some text to remove 1</span>
Some info to keep
<span id="relate1" onClick="reply_click(this)">Some text to remove 1</span>
Some info to keep
<span id="relate2" onClick="reply_click(this)">Some text to remove 2</span>

Working Demo

  

注意:如果你需要从元素中获取任何数据,你将删除..只是   删除之前获取数据不是删除后

像这样

function reply_click(clicked_Element)
    {
        var gettextBeforeRemove = clicked_Element.text();
        clicked_Element.remove();
        alert(gettextBeforeRemove +" Removed");
    }

答案 4 :(得分:0)

请试试这个:

function reply_click(clicked_id)
{
    $('.'+clicked_id).remove();
    alert(clicked_id + "Removed");
}

和html

   <span class="relate1" id="relate1" onClick="reply_click(this.id)">Some text to remove 1</span>
Some info to keep
  <span class="relate1" id="relate1" onClick="reply_click(this.id)">Some    text to remove 1</span>
  Some info to keep
 <span class="relate2" id="relate2" onClick="reply_click(this.id)">Some   text to remove 2</span>