【发布时间】:2014-10-11 14:17:39
【问题描述】:
晚上好!
我的 js/jquery 遇到了一个奇怪的行为,对于一个简单的函数,我正在检索一行的最后一个 ID,以便检查它是否与前一个不同:
oldMsgId = 0;
// Ajax...
currentId = $( ".message_container tr:last" ).attr('id');
checkNewMsg(currentId);
// ... End Ajax.
function checkNewMsg(MsgId) {
if (MsgId != oldMsgId) {
var snd_msg = new Audio('sound/msg.wav');
snd_msg.volume = 0.3;
snd_msg.play();
}
oldMsgId = MsgId ;
}
系统正常工作,但是,当没有新消息检索到时,即最新ID与旧ID相等,它仍然执行条件!
当然,因为oldMsgId设置为0,页面加载后它会执行,但之后通过alerts测试,显示条件不应该运行!
这让我发疯,如果有人有解决方案,我会很高兴听到它:)
编辑:已解决
Well, while using alerts inside the function this time, it appears I have made a huge mistake placing my oldMsgId var inside a loop function (which calls to ajax), so, the variable was reset to 0 everytime and thus made the difference, I'm very sorry xD!
问题已解决,谢谢大家!
【问题讨论】:
-
在 if 语句中添加 2 个显示 MsgId 和 oldMsgId 值的警报,以直观地检查 id 是否确实相同。
-
// Ajax... // ...End Ajax当然,这似乎是相关的。您的问题中没有足够的信息来给出答案。 -
显示更多代码,没有看到此代码的上下文,任何人都猜测可能是什么问题
-
oldMsgId 是一个数值。 MsgId 是一个字符串值。使用 checkNewMsg(parseInt(currentId,10));看看是否有帮助。
-
您应该记录变量的值,而不是责备
!=;) @jeff:没关系,因为类型转换。
标签: javascript conditional operator-keyword behavior