2013-07-29 36 views
0

我正在做一個Firefox擴展,我試圖捕獲上下文菜單中的當前選擇,它工作正常。不過,我希望當前的選擇用雙引號括起來。代碼片段:帶雙引號環繞電流選擇

contentScript: 'self.on("context", function() {' + 
      ' var text = \"'+'window.getSelection().toString()'+'\";' + 
      ' if (text.length > 20)' + 
      ' text = text.substr(0, 20) + "...";' + 
      ' return "Search Google for " + text;' + 
      '});' 

JavaScript已經封閉withing單引號和我曾試圖逃脫雙引號喜歡在上面的代碼片段,但我得到的上下文菜單下面的輸出:

Search Google for window.selection(... 

如何轉義搜索字符串中的雙引號。我試圖在返回的字符串中添加雙引號,但徒勞無功。我認爲它可能是因爲JavaScript代碼本身就是一個字符串。任何幫助深表謝意。

回答

1

你可以這樣做:

var text = "\"" + window.getSelection().toString() + "\""; 

您可以檢查this jsFiddle看到它在行動。

您的代碼應該是這樣的:

contentScript: 'self.on("context", function() {' + 
      ' var text = window.getSelection().toString();' + 
      ' if (text.length > 20) ' + 
      ' text = text.substr(0, 20) + "...";' + 
      ' text = "\"" + text + "\""; ' + 
      ' return "Search Google for " + text;' + 
      ' });' 
+0

我試過了,但它不工作。 – Annihilator8080

+0

我在那裏有一個錯字(缺少+符號)。這是問題嗎? –

+0

看到這個[jsFiddle](http://jsfiddle.net/RhC6E/2/)與幾乎精確的代碼工作 –