首页 > 解决方案 > 如何使用 jquery 从 div 部分中删除特定值

问题描述

我创建了一个包含动态标签的 div。我正在尝试使用 jquery 从 div 部分中删除特定值。如果字符串在 div 部分字符串中匹配,我已经声明了包含字符串的变量,它应该从 div 中删除。有没有办法做到这一点?

      <div class="VS" id="MM" style="border:1px solid gray; width:150px;">
      <label class="custom_label_div2" id="lbl1"> XYZ </label>
      <label class="custom_label_div2" id="lbl2"> XYZC </label>
      <label class="custom_label_div2" id="lbl3"> QWER </label>
      <div>

我试图做这样的事情

    var str = XYZ; --- this is my varibale which will contain any label deriving from somewhere else it can contain any one of the value i.e. XYZ or XYZC or QWER
    $('#MM').each(function() {
       var $this = $(this);
       if ($this.text() === str) {
           $this.remove();
       }
    });

标签: javascriptjqueryhtml

解决方案


if ($this.text() === str) {
           $this.remove();
       }
  • 这是删除元素本身,如果您需要清空它,请使用:
if ($this.text() === str) {
           $this.text("");
       }

或者

if ($this.text() === str) {
           $this.html(""); // if there are other elements inside
       }

要不就

if ($this.text() === str) {
           $this.empty();
       }

推荐阅读