测试元素是否可以包含文本 [英] Test if an element can contain text

查看:90
本文介绍了测试元素是否可以包含文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果HTML元素可以包含一些文本,那么我可以使用纯粹的JavaScript或者jQuery来测试一个干净和健壮的方法吗? < br> < hr> < tr> 不能包含文本节点,而< div> < td> < span> 可以。



测试此属性的最简单的方法是控制标签名称。但这是最好的解决方案吗?我认为这是最差的一个...



编辑:为了澄清问题的意义,需要指出的是,完美的答案应该考虑两个问题:


  1. 根据HTML标准,元素是否包含文本节点?

  2. 如果元素包含一些文本,这是否会显示?

显然,前面列表中每个点都有一个子答案。 >

解决方案

void elements的W3标准指定:


空虚元素

area,base,br,col,embed,hr,img,input,keygen,link,menuitem,meta,param,source,track,wbr


显然,还有一些非官方的标签。



您可以使用黑名单并使用 .prop('tagName')获取标签名称:

 (function($){
var cannotContainText = ['AREA','BASE','BR','COL','EMBED','HR','IMG' 'INPUT','KEYGEN','LINK','MENUITEM','META','PARAM','SOURCE','TRACK','WBR','BASEFONT','BGSOUND','FRAME','ISINDEX ];

$ .fn.canContainText = function(){
var tagName = $(this).prop('tagName')。toUpperCase();

return($ .inArray(tagName,cannotContainText)== -1);
};
}(jQuery));

$('< br>')。canContainText(); // false
$('< div>')。canContainText(); // true

这里您还可以添加自己的标签到 cannotContainText (例如添加< tr> 这不是正式的一个void元素,因为它不匹配规范一个void元素是一个元素,其内容模型永远不允许它具有内容任何情况下,虚空元素都可以有属性。


Is there a clean and robust way in which I can test (using pure javascript or also jQuery) if an HTML element can contain some text?

For instance, <br>, <hr> or <tr> cannot contain text nodes, while <div>, <td> or <span> can.

The simplest way to test this property is to control the tag names. But is this the best solution? I think it is one of the worst...

EDIT: In order to clarify the sense of the question, need to point out that the perfect answer should consider two problems:

  1. According to HTML standards, can the element contain a text node?
  2. If the element contains some text, will this displayed?

Obviously, there is a sub-answer for each point of the previous list.

解决方案

The W3 standard for "void elements" specifies:

Void elements
area, base, br, col, embed, hr, img, input, keygen, link, menuitem, meta, param, source, track, wbr

And apparently there's some unofficial tags as well.

You can make a black list and use .prop('tagName') to get the tag name:

(function ($) {
    var cannotContainText = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];

    $.fn.canContainText = function() {
        var tagName = $(this).prop('tagName').toUpperCase();

        return ($.inArray(tagName, cannotContainText) == -1);
    };
}(jQuery));

$('<br>').canContainText(); //false
$('<div>').canContainText(); //true

Here you can also add your own tags to cannotContainText (eg. to add <tr> which is not officially a void element as it doesn't match the specification "A void element is an element whose content model never allows it to have contents under any circumstances. Void elements can have attributes.").

这篇关于测试元素是否可以包含文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆