开发者

Javascript Variable Scope Confusion

开发者 https://www.devze.com 2023-02-23 01:36 出处:网络
In the following code snippet I\'ve declared the variable \"id\" within the submit function. I attempt to assign a value to it within a nested function but it doesn\'t appear to be within scope and I

In the following code snippet I've declared the variable "id" within the submit function. I attempt to assign a value to it within a nested function but it doesn't appear to be within scope and I don't know why.

$(document).ready(function() {
if (typeof(localStorage) == 'undefined' ) {
    alert('Your browser does not supp开发者_如何学JAVAort HTML5 localStorage. Try upgrading.');
} 
else {

    $("#logForm").submit(function(){
        var id;

        chrome.bookmarks.getRecent(1, function(mostrecent) {
            getLastId(mostrecent);
            });

        function getLastId(mostrecent) {
            mostrecent.forEach(function(mostrecent) {
                lastId = mostrecent.id;
                alert(lastId + ' was last id');
                id = lastId;
                })
            }
        alert(id + ' outside function');

Bonus Question - If you know a better way to pull the last-used id from chrome for a bookmark would love to know what it is. I had to pull recent which doesn't account for the possibility of an added and then deleted last bookmark which would have incremented the index.


This should do it:

$("#logForm").submit(function() {

    var id;

    chrome.bookmarks.getRecent(1, function(arr) {
        id = arr.pop().id;
    });

    // do stuff with id

});
0

精彩评论

暂无评论...
验证码 换一张
取 消