我正在使用 Meteor,我正在尝试检查文本是否为 html。但通常的方法不起作用。这是我的代码:
post: function() {
var postId = Session.get("postId");
var post = Posts.findOne({
_id: postId
});
var object = new Object();
if (post) {
object.title = post.title;
if ($(post.content).has("p")) { //$(post.content).has("p") / post.content instanceof HTMLElement
object.text = $(post.content).text();
if (post.content.match(/<img src="(.*?)"/)) {
object.image = post.content.match(/<img src="(.*?)"/)[1];
}
} else {
console.log("it is not an html------------------------");
object.text = post.content;
}
}
return object;
}
实际上,这是我迄今为止使用过的最“有效”的解决方案。另外,我指出了我使用的两种最常见的方法(在 if 语句旁边)。没有正则表达式是否有可能发生。
可以使用您已经开始使用 jQuery 的方法,但将响应附加到新的方法<div>
并检查该元素是否有子元素。如果 jQuery 找到子元素,那么它就是 html。
如果它是 html,您可以使用以下命令在该 div 中搜索任何类型的元素find()
.
// create element and inject content into it
var $div=$('<div>').html(post.content);
// if there are any children it is html
if($div.children().length){
console.log('this is html');
var $img = $div.find('img');
console.log('There are ' + $img.length +' image(s)');
}else{
console.log('this is not html');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)