不附加HTML字符串

时间:2016-07-12 02:00:18

标签: jquery html string append

我有一个包含HTML

字符串的变量
var myhtml = "<div><a>DEMO</a></div>";

在我附加HTML之前,我想对其进行更改,所以我这样做。

$("body").append( $(myhtml).filter("a").addClass("testing") );

但是,没有附加任何内容,我没有得到控制台错误。如何更改HTML并仍然正常附加?

2 个答案:

答案 0 :(得分:1)

有两件事需要考虑:

  1. filter更改了调用它的jQuery对象。在您的情况下,它只会保留a并删除父div。您应该使用find代替。find将返回一个新的jQuery对象,而不会更改原始对象。
  2. 但是,您无法直接将调用链的结果插入到DOM中。 find返回仅包含a new jQuery对象。如果要保留父div,则必须插入第一个jQuery对象。
  3. var myhtml = "<div><a>DEMO</a></div>";
    // Parse the string into a jquery object.
    var $myhtml = $(myhtml);
    // Add the "testing" class to the `a` child(ren).
    $myhtml.find("a").addClass("testing");
    // Add a class to the root of $myhtml (i.e. the `div`) if needed.
    $myhtml.addClass("div-class");
    // Append the jquery object.
    $("body").append($myhtml);
    .testing {
      background-color: yellow;
    }
    .div-class {
      padding: 5px;
      border-style: solid; 
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

享受=)

var myhtml = "<div><a>DEMO</a></div>";
$("body").append($(myhtml).find('a').addClass("testing"))

好的,用div:

var myhtml = "<div><a>DEMO</a></div>";
var $div = $(myhtml);
$div.find('a').addClass("testing");
$("body").append($div);
祝你好运!