简体   繁体   English

使用jQuery选择子文本

[英]Selecting child text with jQuery

I have a structure like the following: 我的结构如下:

<form>
    <input type="text" />
    <input type="text" />
    ...
    <input type="radio" />
    <input type="whatever" />
    Here I have some text
</form>

I cannot change the structure of the HTML. 我无法更改HTML的结构。 I need to remove via Javascript the text inside the form, and the problem is to select it, since it is not wrapped inside any tag. 我需要通过Javascript删除表单内的文本,问题是要选择它,因为它没有包装在任何标签内。

My solution (more a hack actually) using jQuery is the following 我使用jQuery的解决方案(实际上更多是黑客)如下

$('form').contents().filter(function(){
    return (this.toString() == '[object Text]')
}).remove();

but it's not very robust. 但是它不是很健壮。 In particular it fails on IE (all versions), where this.toString() applied to a chunk of text returns the text itself. 特别是在IE(所有版本)上,此方法均会失败,其中this.toString()应用于文本块会返回文本本身。 Of course I could try 我当然可以尝试

$('form').contents().filter(function(){
    return (this.toString() != '[object]')
}).remove();

but I'm looking for a better solution. 但我正在寻找更好的解决方案。

How am I supposed to remove the text? 我应该如何删除文本?

Both a solution using jQuery or plain Javascript is good for me. 使用jQuery或纯Javascript的解决方案都对我有好处。

Try this, instead of just "this.toString()": 试试这个,而不只是“ this.toString()”:

return (Object.prototype.toString.call(this) == '[object Text]');

You could also check the node type, but I never can remember how to do that; 您也可以检查节点类型,但是我永远不记得该怎么做。 I'll go look it up but somebody's going to beat me to it :-) 我会去查找它,但是有人会击败我:-)

edit told ya! 编辑告诉你!

You filter for this.nodeType == Node.TEXT_NODE . 您过滤this.nodeType == Node.TEXT_NODE Take a look at this answer . 看看这个答案

If you use version 1.4 you can 如果您使用1.4版,则可以

var $temp= $('form').children().detach();
$('form').empty().append($temp);

It will remove all children elements, empty the form (the text..) and reinsert the elements.. 它将删除所有子元素,清空表单(文本..)并重新插入元素。

the same in 1.3.x would require an additional step.. 1.3.x中的相同步骤将需要一个额外的步骤。

var $temp= $('<div />');
$('form').children().appendTo($temp);
$('form').empty().append($temp.children());

[Update] in regards to Andrea's comment [更新]关于Andrea的评论

quoting jquery contents() 引用jquery contents()

The .contents() and .children() methods are similar, except that the former includes text nodes as well as HTML elements in the resulting jQuery object. .contents()和.children()方法类似,除了前者在生成的jQuery对象中包括文本节点以及HTML元素。

How about: 怎么样:

$('form').contents().filter(function(){
    return !this.outerHTML;
}).remove();

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

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