使用与jQuery.html()链接的jQuery.not()

时间:2009-08-12 06:28:31

标签: jquery chaining

是否可以使用与jQuery.not()链接的jQuery.html()

winner.not('a').html()

winner是一个jQuery对象/包装集,我试图返回删除了锚点的HTML。

3 个答案:

答案 0 :(得分:5)

.html()将返回innerHTML - 其中包含任何A标签,你可能会做这样的事情:

// clone the matched div:
var copy = winner.clone();
// remove all A tags from the DOM
copy.find("a").remove();
// get the html.
var noanchors = copy.html();

另外 - 如果你想让A中的文字仍然存在 - 而不是A本身 - 你可以使用:

// for each A tag
copy.find("a").each(function() {
  //insert the text within ourselves to the document directly before us.
  $(this).before($(this).text());
  // then delete ourselves
  $(this).remove();
});

如果<a>中有任何其他标签,那实际上可能会有点混乱 - 它应该说明这个想法。

答案 1 :(得分:0)

这是可能的,但这不会给你你期望的结果。 not('a')会过滤a集合中的winner个标记,但html()会返回集合中第一个项目的值。

因此,如果您的winner[div#i1 div#i2 a div#i3 a]not('a')会将此设置缩减为[div#i1 div#i2 div#i3]html()将返回div#i1的HTML内容。

如果你想从HTML中删除锚点,我认为你应该首先使用.html()方法,然后使用一些将剥去锚点的正则表达式替换返回的值。

答案 2 :(得分:0)

或者,您可以使用以下内容:

var noanchors = '';
winner.not('a').each(function() { noanchors = noanchors + $(this).html(); )

获取非元素'html的串联。但是,这可能会错过各种标记随附项目之间的任何顶级文本。