简体   繁体   English

无法访问函数内部的JavaScript变量

[英]Can't access JavaScript variable inside function

I'm making an extension for selected text search in different search engines. 我正在为不同搜索引擎中的选定文本搜索进行扩展。 One of the menu items changes if the selected string is a particular one. 如果所选字符串是特定字符串,则菜单项之一会更改。 I have this done so far and it does what I want, except I can not make the "title" of the menu change. 到目前为止,我已经完成了此操作,并且可以执行我想要的操作,但是无法更改菜单的“标题”。 How do I give value to the variable "myTitle" in if statement inside the function? 如何在函数内部的if语句中为变量“ myTitle”赋值?

Thanks in advance. 提前致谢。

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);}                             
                 });

You have "cause and effect" mixed up. 您混合了“因果关系”。 When chrome.contextMenus.create is called, myFunction has not executed yet and the value of myTitle has not been assigned. 调用chrome.contextMenus.createmyFunction尚未执行,并且myTitle的值尚未分配。

Perhaps, you can use chrome.contextMenus.update , after the page is loaded. 也许,您可以在页面加载后使用chrome.contextMenus.update You could create the menu, with default titles, but with unique IDs. 您可以创建具有默认标题但具有唯一ID的菜单。 Then use the above method, based on whatever the "selectedText" is, and use the IDs to replace the titles. 然后,根据“ selectedText”的内容使用上述方法,并使用ID替换标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM