簡體   English   中英

無法訪問函數內部的JavaScript變量

[英]Can't access JavaScript variable inside function

我正在為不同搜索引擎中的選定文本搜索進行擴展。 如果所選字符串是特定字符串,則菜單項之一會更改。 到目前為止,我已經完成了此操作,並且可以執行我想要的操作,但是無法更改菜單的“標題”。 如何在函數內部的if語句中為變量“ myTitle”賦值?

提前致謝。

var myTitle; // if I give value here it does work, but I need the value based on the if statement bellow.

function myFunction(selectedText) {

    if(selectedText.match (/someString|SomeOtherString/)) {

        var myURL1 = 'https://someURL' + selectedText;
        chrome.tabs.create({url: myURL1});
        myTitle = "title1"; //I can not make the variable to get this value here

    }else{

         var myURL2 = 'https://someOtherURL' + selectedText;
         chrome.tabs.create({url: topicCall});
         myTitle = "title2"; //I can not make the variable to get this value here
         }
    }


chrome.contextMenus.create({
                **"title": myTitle,**  // this should change based on the selection 
                 contexts:["selection"], 
                 onclick: function (info)myFunction(info.selectionText);}                             
                 });

您混合了“因果關系”。 調用chrome.contextMenus.createmyFunction尚未執行,並且myTitle的值尚未分配。

也許,您可以在頁面加載后使用chrome.contextMenus.update 您可以創建具有默認標題但具有唯一ID的菜單。 然后,根據“ selectedText”的內容使用上述方法,並使用ID替換標題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM