第二个if else语句(没有尝试次数)似乎没有工作

时间:2016-12-21 13:50:16

标签: javascript jquery html

当尝试次数为2时,不会弹出警告。 attempts变量是否没有增加?我无法找到答案。请帮忙。

var attempts = 0;
var $code = "youknowme";

$('.go').on('click', function() {
    if ($('#pass').val() === $code) {
        window.open("3.html");
    } else {
        alert("wrong code");
        attempts = attempts + 1;
    }   
});

if (attempts === 2) {      
    /*this code not working*/
    alert("You have last chance left");
} else if (attempts === 3) {
    window.close();
}

4 个答案:

答案 0 :(得分:3)

这是因为您需要将代码放在click事件中。因为它的if语句只被检查一次,而恰好在你将尝试次数设置为0之后。

如果你正确地格式化了代码,这将使它更容易被发现。

这应该是:

var englishSubtitle = new chrome.cast.media.Track(2,chrome.cast.media.TrackType.TEXT);
englishSubtitle.trackContentId = 'english.vtt';
englishSubtitle.trackContentType = 'text/vtt';
englishSubtitle.subtype = chrome.cast.media.TextTrackType.CAPTIONS;
englishSubtitle.name = 'English';
englishSubtitle.language = 'en-US';
englishSubtitle.customData = null;
var tracks = englishSubtitle;

var mediaInfo = new chrome.cast.media.MediaInfo(app.streamState_.manifest);
mediaInfo.contentType = app.streamState_.type;
mediaInfo.metadata = new chrome.cast.media.GenericMediaMetadata();
mediaInfo.customData = null;
mediaInfo.streamType = chrome.cast.media.StreamType.BUFFERED;
mediaInfo.textTrackStyle = new chrome.cast.media.TextTrackStyle();
mediaInfo.tracks = tracks; 
mediaInfo.metadata.metadataType = chrome.cast.media.MetadataType.GENERIC;

var activeTrackIds = [2];   

var request = new chrome.cast.media.LoadRequest(mediaInfo);
request.autoplay = true;
request.currentTime = 0;
request.activeTrackIds = activeTrackIds;
session.loadMedia(request,onMediaDiscovered.bind(   this, 'loadedMedia'),  onMediaError);

答案 1 :(得分:1)

您的代码应该在函数内部:

{{1}}

答案 2 :(得分:0)

你的if语句需要在onclick监听器中。单击它们时不会执行它们。

答案 3 :(得分:0)

'if'语句不在'click'函数之外。 ```     $('。go')。on('click',function(){         if($('#pass')。val()=== $ code){             window.open( “3.html”);         } else {             警报(“错误代码”);             attempts =尝试+ 1;         }

    if (attempts === 2) {      
        /*this code not working*/
        alert("You have last chance left");
    } else if (attempts === 3) {
        window.close();
    }
});

```