我正在为我的网站编写笑脸解析函数。我想要完成的是转换某些字符串,例如":)"
变成这样的图像:
或者这里是实际的 html 作为例子:
":)" ===> <img src="images/smilies/smile.png" />
我的函数完成了它应该做的事情,但它也在解析原生 javascript 函数名!我的意思是,如果我键入包含字符串 "push"
、 "pop"
或 "some"
(那里可能加载其他)我的函数会将这些字符串解析为无效图像,如下所示:
这是一个显示此内容的 html 字符串:
<img src="images/smilies/function some() { [native code] }" alt="">
这会导致浏览器控制台出现 404 未找到错误。
Failed to load resource: the server responded with a status of 404 (Not Found)
为什么会这样?正如您在此处看到的那样,我在我的代码中没有做任何太不寻常的事情:
function parse_new_comment(commentElem){
$(commentElem).html(parse_comment($(commentElem).text()));
}
function parse_comment(comment){
var formatted_comment = "";
var smilies = new Array();
smilies[":)"] = "smile.png";
smilies[":D"] = "smile-big.png";
smilies[":p"] = "tongue.png";
smilies["[sheep]"] = "sheep.png";
smilies["<3"] = "love.png";
smilies["[love]"] = "love.png";
var words = comment.split(" ");
for (var i = 0; i < words.length; i++) {
if(smilies[words[i]] !== undefined){
formatted_comment += ' <img src="images/smilies/'+smilies[words[i]]+'" alt="" />';
}else{
formatted_comment += ' ' + words[i];
}
}
return formatted_comment;
}
我感觉这行代码导致了问题 if(smilies[words[i]] !== undefined){
,因为 push
和pop
是数组函数,不过我不太确定...如果有人可以就我的函数失败的原因提出任何想法,我将不胜感激。
哦,我忘了说,我的页面使用 ajax 来做所有事情,所以新的评论是通过调用这样的函数来解析的:
parse_new_comment($("#comment_343"));
谢谢。
最佳答案
检查对象本身是否具有属性,而不是对象的属性未定义。这可以使用 hasOwnProperty
来完成.
if(smilies.hasOwnProperty(words[i])){
代替
if(smilies[words[i]] !== undefined){
此外,由于您没有将 smilies
用作数组,所以我同意 Pointy 的评论,即它应该被声明为一个对象。值得一提的是,当您在 JavaScript 中将键附加到 Array
时,它们仅在 they can be seen as unsigned integers 时才被视为数组索引。 .
var smilies = {};//short for new Object();
smilies[":)"] = "smile.png";
smilies[":D"] = "smile-big.png";
smilies[":p"] = "tongue.png";
smilies["[sheep]"] = "sheep.png";
smilies["<3"] = "love.png";
smilies["[love]"] = "love.png";
您可能对使用 Explosion Pills 建议的答案所建议的文字语法感兴趣。澄清一下,仍然需要使用 hasOwnProperty
。
关于javascript - 为什么我的笑脸解析代码调用原生 javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15721347/